package com.laiketui.common.service.dubbo;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.laiketui.common.api.*;
import com.laiketui.common.api.order.PublicIntegralService;
import com.laiketui.common.api.pay.PublicPaymentService;
import com.laiketui.common.mapper.*;
import com.laiketui.common.utils.tool.DateUtil;
import com.laiketui.common.utils.tool.data.OrderDataUtils;
import com.laiketui.common.utils.tool.str.StringUtils;
import com.laiketui.core.cache.RedisUtil;
import com.laiketui.core.common.SplitUtils;
import com.laiketui.core.exception.LaiKeAPIException;
import com.laiketui.core.lktconst.GloabConst;
import com.laiketui.core.utils.tool.DataUtils;
import com.laiketui.core.utils.tool.SerializePhpUtils;
import com.laiketui.domain.config.ConfiGureModel;
import com.laiketui.domain.config.ExpressModel;
import com.laiketui.domain.coupon.CouponModal;
import com.laiketui.domain.home.SystemMessageModel;
import com.laiketui.domain.lktconst.DictionaryConst;
import com.laiketui.domain.lktconst.ErrorCode;
import com.laiketui.domain.log.MchAccountLogModel;
import com.laiketui.domain.log.SignRecordModel;
import com.laiketui.domain.mch.CustomerModel;
import com.laiketui.domain.mch.MchModel;
import com.laiketui.domain.mch.ReturnGoodsModel;
import com.laiketui.domain.mch.ServiceAddressModel;
import com.laiketui.domain.message.MessageLoggingModal;
import com.laiketui.domain.order.*;
import com.laiketui.domain.presell.PreSellRecordModel;
import com.laiketui.domain.product.ProductListModel;
import com.laiketui.domain.product.StockModel;
import com.laiketui.domain.supplier.SupplierAccountLogModel;
import com.laiketui.domain.supplier.SupplierModel;
import com.laiketui.domain.supplier.SupplierOrderFrightModel;
import com.laiketui.domain.user.User;
import com.laiketui.domain.vo.main.RefundVo;
import com.laiketui.domain.vo.order.RefundResultView;
import com.laiketui.domain.vo.plugin.integral.AddScoreVo;
import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

import static com.laiketui.domain.lktconst.DictionaryConst.OrdersStatus.ORDERS_R_STATUS_COMPLETE;
import static com.laiketui.domain.lktconst.DictionaryConst.OrdersStatus.ORDERS_R_STATUS_CONSIGNMENT;


/**
 * 公共售后实现
 *
 * @author Trick
 * @date 2020/12/2 12:05
 */
@Service
public class PublicRefundServiceImpl implements PublicRefundService {

    private final Logger logger = LoggerFactory.getLogger(PublicRefundServiceImpl.class);

    @Autowired
    private PublicOrderService publicOrderService;


    @Autowired
    private MessageLoggingModalMapper messageLoggingModalMapper;


    @Autowired
    private RedisUtil redisUtil;


    @Override
    public boolean refund(RefundVo vo) throws LaiKeAPIException {
        int id = vo.getId();
        int storeId = vo.getStoreId();
        try {
            Map<String, Object> parmaMap = new HashMap<>(16);
            parmaMap.put("store_id", vo.getStoreId());
            //店铺联系方式
            String mchPhone = "";
            //是否短信配置 ---> 禅道47551 测试说没有发送短信给商家的功能
            boolean isSendNotice = false;
            //防止连续点击造成多次退款 -并发处理
            if (redisUtil.incr(GloabConst.RedisHeaderKey.REFUND_ORDER_KEY + storeId + "_" + id, 1) > 1){
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_CFCZ, "重复操作", "refund");
            }
            //售后记录
            ReturnRecordModel returnRecordSave = new ReturnRecordModel();
            returnRecordSave.setStore_id(vo.getStoreId());
            //判断是否设置售后地址
            ServiceAddressModel serviceAddressModel = new ServiceAddressModel();
            serviceAddressModel.setStore_id(vo.getStoreId());
            serviceAddressModel.setUid("admin");
            serviceAddressModel.setIs_default(DictionaryConst.DefaultMaven.DEFAULT_OK);
            serviceAddressModel.setType(DictionaryConst.ServiceAddressType.ServiceAddressType_AfterSale);
            int count = serviceAddressModelMapper.selectCount(serviceAddressModel);
            if (count < 0) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_QSZSHDZ, "请设置售后地址", "refund");
            }
            //获取电商平台管理员信息
            CustomerModel customerModel = new CustomerModel();
            customerModel.setId(vo.getStoreId());
            customerModel.setRecycle(DictionaryConst.ProductRecycle.NOT_STATUS);
            customerModel = customerModelMapper.selectOne(customerModel);
            if (customerModel != null) {
                mchPhone = customerModel.getMobile();
            }
            Integer orderDetailId = null;
            //进入订单详情把未读状态改成已读状态，已读状态的状态不变
            parmaMap.put("id", vo.getId());
            List<Map<String, Object>> orderInfoList = returnOrderModelMapper.getReturnOrderJoinOrderListDynamic(parmaMap);
            if (orderInfoList != null && orderInfoList.size() > 0) {
                Map<String, Object> returnOrderInfoMap = orderInfoList.get(0);
                //订单读取状态
                int read = StringUtils.stringParseInt(returnOrderInfoMap.get("readd") + "");
                //售后id
                int refundId = MapUtils.getIntValue(returnOrderInfoMap, "refundId");
                //售后类型
                int reType = MapUtils.getIntValue(returnOrderInfoMap, "re_type");
                //售后状态
                int r_type = MapUtils.getIntValue(returnOrderInfoMap,"r_type");
                //订单id
                int orderId = StringUtils.stringParseInt(returnOrderInfoMap.get("oId").toString());
                //订单id
                String orderno = returnOrderInfoMap.get("sNo").toString();
                //订单详情id
                int detailId = orderDetailId = StringUtils.stringParseInt(returnOrderInfoMap.get("detialId").toString());
                //详情状态
                int rStatus = MapUtils.getInteger(returnOrderInfoMap, "r_status");
                //订单金额
                BigDecimal orderPrice = new BigDecimal(returnOrderInfoMap.get("z_price").toString());
                //订单原始支付金额
                BigDecimal old_total = new BigDecimal(returnOrderInfoMap.get("old_total").toString());
                //单个商品的实际支付金额
                BigDecimal goodsPayPrice = getOrderPrice(vo.getStoreId(), detailId);
                //买家userid
                String clientUserId = returnOrderInfoMap.get("user_id").toString();
                returnRecordSave.setUser_id(clientUserId);
                //买家名称
                String clientUserName = returnOrderInfoMap.get("name").toString();
                //买家手机号
                String clientUserPhon = returnOrderInfoMap.get("mobile").toString();
                //店铺id
                int mchId = StringUtils.stringParseInt(StringUtils.trim(returnOrderInfoMap.get("mch_id").toString(), SplitUtils.DH));
                //商品id
                int goodsId = StringUtils.stringParseInt(returnOrderInfoMap.get("goodsId").toString());
                //是否是该订单下最后一个同商品不同规格还未结算和关闭的的商品 用于判断是否退给用户运费
                List<OrderDetailsModel> orderDetailsForPro = orderDetailsModelMapper.getSameProDetailNotCloseAndSettlement(vo.getStoreId(), orderno, goodsId);
                //是否为供应商商品
                boolean isSupplierPro = false;
                ProductListModel proModel = productListModelMapper.selectByPrimaryKey(goodsId);
                if (StringUtils.isNotEmpty(proModel.getGongyingshang()) && !Objects.isNull(proModel.getSupplier_superior())) {
                    isSupplierPro = true;
                }
                //供应商结算供货价
                String supplierSettlement = MapUtils.getString(returnOrderInfoMap, "supplier_settlement");
                //属性id
                int attributeId = StringUtils.stringParseInt(returnOrderInfoMap.get("attributeId").toString());
                //支付方式
                String payType = returnOrderInfoMap.get("pay").toString();
                //订单商品使用的优惠卷id
                String couponId = returnOrderInfoMap.get("detailCouponId") + "";
                //满减活动id
                int subtractionId = StringUtils.stringParseInt(returnOrderInfoMap.get("subtraction_id") + "");
                //订单商品运费
                BigDecimal freight = new BigDecimal(returnOrderInfoMap.get("freight").toString());
                //抵扣余额
                BigDecimal offsetBalance = new BigDecimal(returnOrderInfoMap.get("offset_balance") + "");
                //支付流水号
                String realOrderno = MapUtils.getString(returnOrderInfoMap, "real_sno", "");
                //父订单id
                String psNo = MapUtils.getString(returnOrderInfoMap, "p_sNo");
                String otype = MapUtils.getString(returnOrderInfoMap, "otype", "");
                //调起支付支付金额
                BigDecimal upPaymentPrice = old_total;
                OrderModel orderModel = new OrderModel();
               // 订单拆单过
                if (StringUtils.isNotEmpty(psNo)){
                    //根据调起支付所用订单号获取主订单号(未支付先拆单，子订单调起支付所用调起支付所用订单号和总订单相同)
                    String sNo = orderModelMapper.getOrderByRealSno(realOrderno);
                    logger.info("根据吊起支付订单号获取主订单号:{}", sNo);
                    if (StringUtils.isNotEmpty(sNo)){
                        orderModel = new OrderModel();
                        orderModel.setsNo(sNo);
                        orderModel = orderModelMapper.selectOne(orderModel);
                        upPaymentPrice = orderModel.getOld_total();
                    }
                }

                //到货时间
//                String arriveTime = returnOrderInfoMap.get("arrive_time") + "";
//                boolean isArruve = !StringUtils.isEmpty(arriveTime) && !"0000-00-00 00:00:00".equals(arriveTime);
                //是否已到货标识 只有确认收货后钱才会到店铺余额,过了售后则到可提现金额
                boolean isArruve = OrderModel.ORDER_FINISH == rStatus;
                int settlementType = MapUtils.getIntValue(returnOrderInfoMap, "settlement_type");
                //订单是否已经结算标识
                boolean isSettlement = settlementType != 0;
                if (isSettlement) {
                    throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_DDYJJS, "订单已经结算");
                }

//                $psNo = $r1[0]->p_sNo; // 父订单号

                //其它支付所支付金额
                BigDecimal outherPay = orderPrice.subtract(offsetBalance);
                //订单商品总价
                BigDecimal orderDetailPrice = new BigDecimal(returnOrderInfoMap.get("p_price").toString());
                //商品数量
                BigDecimal goodsNeedNum = new BigDecimal(returnOrderInfoMap.get("num").toString());
                orderDetailPrice = orderDetailPrice.multiply(goodsNeedNum);

                if (!DictionaryConst.ReturnRecordReType.RETURNORDERSTATUS_GOODS_REBACK.equals(reType)) {
                    //退款金额限制
                    if (orderPrice.compareTo(vo.getPrice()) < 0) {
                        logger.debug("订单详情id{}退款失败,金额错误 退款金额{} 实际订单支付金额{}", detailId, vo.getPrice(), goodsPayPrice);
                        throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_SRDJEYWQZXSR, "输入的金额有误,请重新输入");
                    } else if (otype.equals(DictionaryConst.OrdersType.ORDERS_HEADER_GM) && goodsPayPrice.compareTo(vo.getPrice()) < 0) {
                        logger.debug("订单详情id{}退款失败,金额错误 退款金额{} 实际商品支付金额{}", detailId, vo.getPrice(), goodsPayPrice);
                        throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_SRDJEYWQZXSR, "输入的金额有误,请重新输入");
                    }
                }

                if (read == 0) {
                    orderModel = new OrderModel();
                    orderModel.setId(orderId);
                    orderModel.setReadd(OrderModel.READ);
                    count = orderModelMapper.updateByPrimaryKeySelective(orderModel);
                    if (count < 1) {
                        logger.info("修改订单已读状态失败 参数:" + JSON.toJSONString(orderModel));
                    }
                }
                //当不是后台操作时
                if (vo.getMchId() != 0) {
                    //验证店铺
                    if (vo.getMchId() != mchId) {
                        logger.info("订单所属店铺不一致 参数:" + vo.getMchId() + ">>>" + mchId);
                        throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_MDBHBZQ, "门店编号不正确", "refund");
                    }
                }
                //获取店铺信息
                MchModel mchModel = new MchModel();
                mchModel.setStore_id(vo.getStoreId());
                mchModel.setId(mchId);
                mchModel = mchModelMapper.selectOne(mchModel);
                if (mchModel == null) {
                    throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_DPSJYC, "店铺数据异常", "refund");
                }
                //站内推送消息
                String tuiTitle = "退货/退款成功!";
                String tuiContext = "您的退货/退款申请已通过!";
                SystemMessageModel systemMessageSave = new SystemMessageModel();
                systemMessageSave.setStore_id(vo.getStoreId());
                systemMessageSave.setSenderid("admin");
                systemMessageSave.setRecipientid(clientUserId);
                systemMessageSave.setTitle(tuiTitle);
                systemMessageSave.setContent(tuiContext);
                systemMessageSave.setType(SystemMessageModel.ReadType.UNREAD);

                //供应商端除外其他端操作供应商售后订单只做店铺是否同意处理
                if (StringUtils.isEmpty(vo.getOperator())) {
                    ProductListModel productListModel = productListModelMapper.selectByPrimaryKey(goodsId);
                    if (StringUtils.isNotEmpty(productListModel.getGongyingshang()) && vo.getType().equals(DictionaryConst.ReturnOrderStatus.RETURNORDERSTATUS_AGREE_REBACK)) {
                        //修改售后状态
                        ReturnOrderModel updateReturnOrder = new ReturnOrderModel();
                        updateReturnOrder.setId(vo.getId());
                        updateReturnOrder.setIs_agree(DictionaryConst.WhetherMaven.WHETHER_OK);
                        returnOrderModelMapper.updateByPrimaryKeySelective(updateReturnOrder);
                        MessageLoggingModal messageLoggingSave = new MessageLoggingModal();
                        messageLoggingSave.setStore_id(vo.getStoreId());
                        messageLoggingSave.setType(MessageLoggingModal.Type.TYPE_ORDER_RETURN);
                        messageLoggingSave.setTo_url(OrderDataUtils.getOrderRoute(orderno, 0));
                        messageLoggingSave.setParameter(orderId + "");
                        messageLoggingSave.setContent(String.format("订单 %s已申请退款（或者退货退款或者换货），请前往退货列表中及时处理！", orderno));
                        messageLoggingSave.setAdd_date(new Date());
                        messageLoggingSave.setSupplier_id(Integer.valueOf(productListModel.getGongyingshang()));
                        messageLoggingModalMapper.insertSelective(messageLoggingSave);
                        if (vo.getType().equals(DictionaryConst.ReturnOrderStatus.RETURNORDERSTATUS_RECEIVED_REBAKGOODS) ||
                                DictionaryConst.ReturnOrderStatus.RETURNORDERSTATUS_AGREE_REBACK_GOODS.equals(vo.getType())) {
                            return true;
                        }
                    }
                }

                //实际退款金额
                BigDecimal realMoney = BigDecimal.ZERO;
                //订单售后流程
                if (vo.getType().equals(DictionaryConst.ReturnOrderStatus.RETURNORDERSTATUS_AGREE_REBACK)
                        || vo.getType().equals(DictionaryConst.ReturnOrderStatus.RETURNORDERSTATUS_USER_DELIVERED)
                        || vo.getType().equals(DictionaryConst.ReturnOrderStatus.RETURNORDERSTATUS_RECEIVED_REBAKGOODS)
                        || vo.getType().equals(DictionaryConst.ReturnOrderStatus.RETURNORDERSTATUS_QUICK_SUPPLIER_AGRESS)
                        || vo.getType().equals(DictionaryConst.ReturnOrderStatus.RETURNORDERSTATUS_AGREE_REBACK_AMT)
                        //人审核流程
                        || vo.getType().equals(DictionaryConst.ReturnOrderStatus.RETURNORDERSTATUS_REFUSE_ARTIFICIAL_OK)
                ) {
                    if (vo.getType().equals(DictionaryConst.ReturnOrderStatus.RETURNORDERSTATUS_REFUSE_ARTIFICIAL_OK) && !this.isMainExamine(vo.getStoreId(), refundId)) {
                        logger.debug("售后id:{},不能人工受理!", refundId);
                        throw new LaiKeAPIException(ErrorCode.BizErrorCode.ILLEGAL_INVASION, "非法入侵");
                    }
                    logger.info("=====退款开始=====");
                    if (DictionaryConst.ReturnRecordReType.RETURNORDERSTATUS_GOODS_REBACK.equals(reType) && vo.getType().equals(DictionaryConst.ReturnOrderStatus.RETURNORDERSTATUS_AGREE_REBACK)) {
                        tuiTitle = "换货";
                        tuiContext = "您的换货申请已通过!";
                    }
                    //同意退款
                    if (vo.getType().equals(DictionaryConst.ReturnOrderStatus.RETURNORDERSTATUS_RECEIVED_REBAKGOODS)
                            || vo.getType().equals(DictionaryConst.ReturnOrderStatus.RETURNORDERSTATUS_AGREE_REBACK_AMT)
                            //人工受理
                            || vo.getType().equals(DictionaryConst.ReturnOrderStatus.RETURNORDERSTATUS_REFUSE_ARTIFICIAL_OK)) {
                        logger.info("===同意退款===");
                        //获取实际支付金额
                        logger.debug("同意订单详情id{}退款,订单商品付款金额{},实际退款金额{}", detailId, goodsPayPrice, vo.getPrice());
                        // 组合支付不要了
                        if (DictionaryConst.OrderPayType.ORDERPAYTYPE_TT_ALIPAY.equals(payType)) {
                            payType = DictionaryConst.OrderPayType.ORDERPAYTYPE_ALIPAY;
                        } else if (DictionaryConst.OrderPayType.ORDERPAYTYPE_BAIDU_PAY.equals(payType)) {
                            payType = DictionaryConst.OrderPayType.ORDERPAYTYPE_WALLET_PAY;
                        }
                        //获取短信列表
                        Map<String, Object> messageInfo = messageListModelMapper.getMessageListInfoByType(vo.getStoreId(), GloabConst.VcodeCategory.TYPE_NOTICE, GloabConst.VcodeCategory.PAY_REFUND_ORDER);
                        String content;
                        String parmaJson;
                        Map<String, String> smsParmaMap = null;
                        if (messageInfo != null) {
                            isSendNotice = true;
                            content = messageInfo.get("content").toString();
                            parmaJson = JSON.toJSONString(SerializePhpUtils.getUnserializeObj(content, Map.class));
                            smsParmaMap = JSON.parseObject(parmaJson, new TypeReference<Map<String, String>>() {
                            });
                        } else {
                            logger.error("商城【{}】未配置通知短信服务!", vo.getStoreId());
                        }

                        logger.info("退款信息payType，{}", payType);

                        MchAccountLogModel mchAccountLogModel = new MchAccountLogModel();
                        mchAccountLogModel.setStore_id(vo.getStoreId());
                        mchAccountLogModel.setMch_id(mchModel.getId().toString());
                        realMoney = vo.getPrice();
                        //刷新店铺信息
                        mchModel = mchModelMapper.selectByPrimaryKey(mchModel.getId());

                        //添加一条退款记录---少退的情况 是否少退,如果少退则增加店铺收入-立即结算到可提现金额
                        BigDecimal tuiMoney = goodsPayPrice.subtract(vo.getPrice());
                        if (tuiMoney.compareTo(BigDecimal.ZERO) > 0) {
                            //标记该商品已经结算
                            isSettlement = true;
                            //刷新店铺信息
                            mchModel = mchModelMapper.selectByPrimaryKey(mchModel.getId());
                            //退款-少退的部分记录到账【入账】 这里记录的是店铺钱包,但是实际上到账是到可提现账户【这里最好记录可提现账户的流水】
                            //禅道40081  不记录退款少退入账部分
                            //订单未结算 记录少退  禅道48324
                            if (rStatus == OrderModel.ORDER_PAYED || rStatus == OrderModel.ORDER_UNRECEIVE){
                                mchAccountLogModel.setId(null);
                                mchAccountLogModel.setPrice(tuiMoney);
                                mchAccountLogModel.setRemake(orderno);
                                mchAccountLogModel.setAccount_money(mchModel.getAccount_money());
                                mchAccountLogModel.setType(DictionaryConst.MchAccountLogType.MCHACCOUNTLOG_TYPE_REFUND);
                                mchAccountLogModel.setStatus(DictionaryConst.MchAccountLogStatus.MCHACCOUNTLOG_STATUS_INCOME);
                                mchAccountLogModel.setAddtime(new Date());
                                count = mchAccountLogModelMapper.insertSelective(mchAccountLogModel);
                                if (count < 1) {
                                    logger.info("退款记录失败(少退的情况) 参数:" + JSON.toJSONString(mchAccountLogModel));
                                    throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_TKSBWLGZ, "退款失败,网络故障");
                                }
                            }
                            logger.debug("退款增加店铺收入(少退的情况) 结算到店铺id:{} 可提现金额:{}", mchId, tuiMoney);
                            //只有确认收货的时候才会增加店铺余额,少退的清空下只增加可提现金额
                            if (rStatus == OrderModel.ORDER_FINISH) {
                                count = mchModelMapper.settlementMch(vo.getStoreId(), mchId, tuiMoney);
                            } else {
                                //增加店铺收入[可提现账户]
                                count = mchModelMapper.settlementMchCash(vo.getStoreId(), mchId, tuiMoney);
                            }
                            if (count < 1) {
                                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_TKSB, "退款失败");
                            }
                        }
                        //供应商商品售后 仅退款需结算给供应商当前订单的供货价及运费 退货退款需结算给供应商当前订单的运费
                        if (isSupplierPro) {
                            //如果供应商未发货就退款  则订单详情需结算给供应商的钱归零
                            if (rStatus < OrderModel.ORDER_UNRECEIVE){
                                OrderDetailsModel orderDetailsModel = orderDetailsModelMapper.selectByPrimaryKey(detailId);
                                orderDetailsModel.setSupplier_settlement(BigDecimal.ZERO);
                                count = orderDetailsModelMapper.updateByPrimaryKeySelective(orderDetailsModel);
                                if (count < 1) {
                                    logger.info("供应商结算金额归零 参数:" + JSON.toJSONString(orderDetailsModel));
                                    throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLGZTKSB, "供应商结算金额异常,退款失败", "refund");
                                }
                            }
                            //结算金额
                            BigDecimal settlementPrice = BigDecimal.ZERO;
                            if ((vo.getType().equals(DictionaryConst.ReturnOrderStatus.RETURNORDERSTATUS_AGREE_REBACK_AMT) && rStatus >= OrderModel.ORDER_UNRECEIVE) ||
                                    vo.getType().equals(DictionaryConst.ReturnOrderStatus.RETURNORDERSTATUS_RECEIVED_REBAKGOODS)) {
                                //2023/08/03新需求:退款成功是不会给店铺和供应商退运费(发了货也不退) 需等到整比订单过了售后期才会结算运费
//                                SupplierOrderFrightModel supplierOrderFrightModel = new SupplierOrderFrightModel();
//                                supplierOrderFrightModel.setStore_id(vo.getStoreId());
//                                supplierOrderFrightModel.setsNo(orderno);
//                                supplierOrderFrightModel.setDetail_id(goodsId);
//                                supplierOrderFrightModel = supplierOrderFrightModelMapper.selectOne(supplierOrderFrightModel);
//                                if (supplierOrderFrightModel != null &&
//                                        supplierOrderFrightModel.getIs_settlement().equals(DictionaryConst.WhetherMaven.WHETHER_NO) &&
//                                        supplierOrderFrightModel.getFreight().compareTo(BigDecimal.ZERO) > 0) {
//                                    //增加供应商余额
//                                    supplierModelMapper.addPrice(Integer.parseInt(proModel.getGongyingshang()), supplierOrderFrightModel.getFreight());
//                                    SupplierModel supplierModel = supplierModelMapper.selectByPrimaryKey(proModel.getGongyingshang());
//                                    //生成余额明细
//                                    supplierAccountLogModelMapper.saveAccountLog(vo.getStoreId(), Integer.parseInt(proModel.getGongyingshang()), supplierOrderFrightModel.getFreight(), supplierModel.getSurplus_balance(), SupplierAccountLogModel.ENTRY, SupplierAccountLogModel.ORDER, new Date(), orderno, "店铺结算退款订单运费");
//                                    supplierOrderFrightModel.setIs_settlement(DictionaryConst.WhetherMaven.WHETHER_OK);
//                                    supplierOrderFrightModelMapper.updateByPrimaryKeySelective(supplierOrderFrightModel);
//                                    settlementPrice = supplierOrderFrightModel.getFreight();
//                                }
                                //订单结算之前供货价是不会到供应商去 所以售后退款不需要
                                if (vo.getType().equals(DictionaryConst.ReturnOrderStatus.RETURNORDERSTATUS_AGREE_REBACK_AMT)) {
                                    BigDecimal supplyPrice = new BigDecimal(supplierSettlement);
                                    //增加供应商余额
                                    supplierModelMapper.addPrice(Integer.parseInt(proModel.getGongyingshang()), supplyPrice);
                                    SupplierModel supplierModel = supplierModelMapper.selectByPrimaryKey(proModel.getGongyingshang());
                                    //生成余额明细
                                    supplierAccountLogModelMapper.saveAccountLog(vo.getStoreId(), Integer.parseInt(proModel.getGongyingshang()), supplyPrice, supplierModel.getSurplus_balance(), SupplierAccountLogModel.ENTRY, SupplierAccountLogModel.ORDER, new Date(), orderno, "店铺结算退款订单供货价");
                                    settlementPrice = settlementPrice.add(supplyPrice);
                                }
                                if (settlementPrice.compareTo(BigDecimal.ZERO) > 0) {
                                    //扣除店铺余额
                                    Map<String, Object> mchMap = new HashMap<>(16);
                                    mchMap.put("t_money", settlementPrice);
                                    mchMap.put("store_id", vo.getStoreId());
                                    mchMap.put("mch_id", mchId);
                                    count = mchModelMapper.withdrawal(mchMap);
                                    if (count > 0) {
                                        logger.info("供应商订单进行退款操作,店铺{}对供应商{}进行结算", mchId, proModel.getGongyingshang());
                                    }
                                    //记录店铺收支信息
                                    mchAccountLogModel = new MchAccountLogModel();
                                    mchAccountLogModel.setStore_id(vo.getStoreId());
                                    mchAccountLogModel.setMch_id(String.valueOf(mchId));
                                    mchAccountLogModel.setRemake(orderno);
                                    mchAccountLogModel.setPrice(settlementPrice);
                                    mchAccountLogModel.setStatus(DictionaryConst.MchAccountLogStatus.MCHACCOUNTLOG_STATUS_EXPENDITURE);
                                    mchAccountLogModel.setAccount_money(mchModel.getAccount_money());
                                    mchAccountLogModel.setType(DictionaryConst.MchAccountLogType.MCHACCOUNTLOG_TYPE_SUPPLIER);
                                    mchAccountLogModel.setAddtime(new Date());
                                    mchAccountLogModelMapper.insertSelective(mchAccountLogModel);
                                }
                            }
                        }

                        //只有退货退款需要退库存
                        //优化仅退款也需要回滚商品库存 禅道#35100
                        if (vo.getType().equals(DictionaryConst.ReturnOrderStatus.RETURNORDERSTATUS_RECEIVED_REBAKGOODS) ||
                                (vo.getType().equals(DictionaryConst.ReturnOrderStatus.RETURNORDERSTATUS_AGREE_REBACK_AMT) &&
                                        rStatus < OrderModel.ORDER_UNRECEIVE)) {
                            //获取商品库存信息
                            ConfiGureModel confiGureModel = new ConfiGureModel();
                            confiGureModel.setId(attributeId);
                            confiGureModel = confiGureModelMapper.selectOne(confiGureModel);
                            if (confiGureModel == null) {
                                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_SPKCBCZ, "商品库存不存在", "refund");
                            }
                            //供应商商品处理
                            Integer cid = confiGureModel.getId();
                            Integer goodId = goodsId;
                            if (isSupplierPro) {
                                //子供应商商品也需要回滚
                                count = productListModelMapper.updateProductListVolume(goodsNeedNum.negate().intValue(), vo.getStoreId(), goodId);
                                if (count < 1) {
                                    logger.info("销量扣减失败 商品id:" + goodId + " 销量扣减数量:" + goodsNeedNum);
                                    throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLGZTKSB, "网络故障,退款失败", "refund");
                                }
                                count = confiGureModelMapper.reduceGoodsStockNum(goodsNeedNum.negate().intValue(), cid);
                                if (count < 1) {
                                    logger.info("回滚属性库存失败 商品id:" + goodId + " 退货数量:" + goodsNeedNum);
                                    throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLGZTKSB, "网络故障,退款失败", "refund");
                                }
                                count = productListModelMapper.addGoodsStockNum(goodId, goodsNeedNum.intValue());
                                if (count < 1) {
                                    logger.info("商品库存回滚失败 商品id:" + goodId + " 销量扣减数量:" + goodsNeedNum);
                                    throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLGZTKSB, "网络故障,退款失败", "refund");
                                }
                                confiGureModel = confiGureModelMapper.selectByPrimaryKey(confiGureModel.getSupplier_superior());
                                cid = confiGureModel.getId();
                                goodId = proModel.getSupplier_superior();
                                logger.info("正在处理供应商商品id" + goodId + "----->规格id" + cid + "回滚库存、扣减销量、增加总库存操作");
                            }
                            //预售商品需要回滚所有规格库存
                            if (proModel.getIs_presell().equals(DictionaryConst.WhetherMaven.WHETHER_OK)) {
                                count = confiGureModelMapper.reduceProAllAttrNum(goodsNeedNum.negate().intValue(), goodsId);
                                if (count < 1) {
                                    logger.info("回滚属性库存失败 商品id:" + goodId + " 退货数量:" + goodsNeedNum);
                                    throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLGZTKSB, "网络故障,退款失败", "refund");
                                }
                            } else {
                                //回滚库存
                                count = confiGureModelMapper.reduceGoodsStockNum(goodsNeedNum.negate().intValue(), cid);
                                if (count < 1) {
                                    logger.info("回滚属性库存失败 商品id:" + goodId + " 退货数量:" + goodsNeedNum);
                                    throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLGZTKSB, "网络故障,退款失败", "refund");
                                }
                            }
                            //减销量
                            count = productListModelMapper.updateProductListVolume(goodsNeedNum.negate().intValue(), vo.getStoreId(), goodId);
                            if (count < 1) {
                                logger.info("销量扣减失败 商品id:" + goodId + " 销量扣减数量:" + goodsNeedNum);
                                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLGZTKSB, "网络故障,退款失败", "refund");
                            }
                            // 增加商品库存
                            count = productListModelMapper.addGoodsStockNum(goodId, goodsNeedNum.intValue());
                            if (count < 1) {
                                logger.info("商品库存回滚失败 商品id:" + goodId + " 销量扣减数量:" + goodsNeedNum);
                                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLGZTKSB, "网络故障,退款失败", "refund");
                            }
                            //退款成功 增加商品总库存
                            String text = "退款成功,增加商品库存" + goodsNeedNum;
                            StockModel stockModel = new StockModel();
                            stockModel.setStore_id(vo.getStoreId());
                            stockModel.setProduct_id(goodId);
                            stockModel.setAttribute_id(cid);
                            stockModel.setTotal_num(confiGureModel.getTotal_num());
                            stockModel.setFlowing_num(goodsNeedNum.intValue());
                            stockModel.setType(StockModel.StockType.STOCKTYPE_WAREHOUSING);
                            stockModel.setContent(text);
                            stockModel.setAdd_date(new Date());
                            count = stockModelMapper.insertSelective(stockModel);
                            if (count < 1) {
                                logger.info("添加商品库存失败 参数:" + JSON.toJSONString(stockModel));
                                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLGZTKSB, "网络故障,退款失败", "refund");
                            }
                        }
                        //修改订单状态为关闭
                        OrderDetailsModel orderDetailsModel = new OrderDetailsModel();
                        orderDetailsModel.setId(detailId);
                        if (isSettlement) {
                            orderDetailsModel.setSettlement_type(OrderDetailsModel.SETTLEMENT_TYPE_SETTLED);
                        }
                        orderDetailsModel.setR_status(DictionaryConst.OrdersStatus.ORDERS_R_STATUS_CLOSE);
                        orderDetailsModel.setAudit_time(new Date());
                        count = orderDetailsModelMapper.updateByPrimaryKeySelective(orderDetailsModel);
                        if (count < 1) {
                            logger.info("关闭订单失败 参数:" + JSON.toJSONString(orderDetailsModel));
                            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLGZTKSB, "网络故障,退款失败", "refund");
                        }
//                        if (rStatus >= OrderModel.ORDER_UNRECEIVE) {
//                            logger.debug("订单一发货,不退运费");
//                            freight = BigDecimal.ZERO;
//                        }


                        //如果订单商品使用了优惠卷
                        if (!StringUtils.isEmpty(couponId)) {
                            if (!("0,0".equals(couponId) || "0".equals(couponId))) {
                                // 当订单详情使用了优惠券
                                // 订单详情使用的优惠券ID字符串 转数组
                                String[] couponList = couponId.split(SplitUtils.DH);
                                for (int i = 0; i < couponList.length; i++) {
                                    String tmpCouponId = couponList[i];
                                    if (!"0".equals(tmpCouponId) && null != tmpCouponId) {
                                        // 使用了优惠券
                                        if (i == 0 || (i == 1 && "".equals(psNo))) {
                                            // 使用了店铺优惠券 或 (使用了平台优惠券 并且 不是跨店铺订单)
                                            // 根据商城ID、订单号、店铺优惠券ID，查询不是这个订单详情的数据
                                            List<Map<String, Object>> otherOrders = orderDetailsModelMapper.getOrderDetailsUseTheCoupon(vo.getStoreId(), orderno, tmpCouponId, orderId);
                                            boolean flag = false;
                                            //所有详单的优惠和金额为0
                                            boolean allAfterDiscountIsZero = true;
                                            if (otherOrders != null && otherOrders.size() > 0) {
                                                // 存在(该订单里，还有其它详情使用了这张店铺优惠券)
                                                // 该订单里，有多少详情使用了这张店铺优惠券
                                                int size = otherOrders.size();
                                                // 该订单里，使用了这张店铺优惠券,并退款或退货退款成功的数量
                                                int returnNum = 0;
                                                for (Map<String, Object> otherOrderDetail : otherOrders) {
                                                    int orderStatus = MapUtils.getIntValue(otherOrderDetail, "r_status");
                                                    if (orderStatus == DictionaryConst.OrdersStatus.ORDERS_R_STATUS_CLOSE) {
                                                        returnNum++;
                                                    }
                                                    //优惠后金额不为0
                                                    if (BigDecimal.ZERO.compareTo(new BigDecimal(MapUtils.getString(otherOrderDetail, "after_discount"))) != 0){
                                                        allAfterDiscountIsZero = false;
                                                    }
                                                }
                                                if (returnNum == size) {
                                                    flag = true;
                                                }
                                            } else {
                                                flag = true;
                                            }
                                            if (flag) {
                                                // 该订单，使用了这张店铺优惠券的订单商品都退款或退款退款成功
                                                int row = publicCouponService.couponWithOrder(vo.getStoreId(), clientUserId, tmpCouponId, orderno, "update");
                                                if (row == 0) {
                                                    //回滚删除已经创建的订单
                                                    throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLGZTKSB, "网络故障,退款失败", "refund");
                                                }
                                                // =2
                                                row = publicCouponService.updateCoupons(vo.getStoreId(), clientUserId, tmpCouponId, CouponModal.COUPON_TYPE_NOT_USED);
                                                if (row == 0) {
                                                    //回滚删除已经创建的订单
                                                    throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLGZTKSB, "网络故障,退款失败", "refund");
                                                }
                                                //使用了平台优惠卷，优惠金额大于总价。当订单所有商品退款成功时须将支付的0.01元退还 2023-09-12 gp
                                                if (i == 1 && allAfterDiscountIsZero && orderPrice.compareTo(new BigDecimal("0.01")) == 0){
                                                    vo.setPrice(vo.getPrice().add(orderPrice));
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        //判断是否为预售商品，修改预售订单表的数据
                        PreSellRecordModel preSellRecordModel = new PreSellRecordModel();
                        preSellRecordModel.setsNo(orderno);
                        List<PreSellRecordModel> select = preSellRecordModelMapper.select(preSellRecordModel);
                        if (!Objects.isNull(select) && select.size() > 0) {
                            for (PreSellRecordModel model : select){
                                model.setIs_refund(1);
                                preSellRecordModelMapper.updateByPrimaryKeySelective(model);
                            }
                        }
                        //如果是退款详单是该订单下同商品不同规格最后一个商品则会退给用户运费 反之则不退
                        if (orderDetailsForPro.size() == 1) {
                            //供应商商品运费逻辑处理 如果为订单中最后一个同商品不同规格的数据进行退款 则供应商运费数据标记已结算
                            if (isSupplierPro) {
                                SupplierOrderFrightModel supplierOrderFrightModel = new SupplierOrderFrightModel();
                                supplierOrderFrightModel.setStore_id(vo.getStoreId());
                                supplierOrderFrightModel.setsNo(orderno);
                                supplierOrderFrightModel.setDetail_id(goodsId);
                                supplierOrderFrightModel = supplierOrderFrightModelMapper.selectOne(supplierOrderFrightModel);
                                if (supplierOrderFrightModel != null) {
                                    vo.setPrice(vo.getPrice().add(supplierOrderFrightModel.getFreight()));
                                    realMoney = realMoney.add(supplierOrderFrightModel.getFreight());
                                    supplierOrderFrightModel.setFreight(BigDecimal.ZERO);
                                    supplierOrderFrightModel.setIs_settlement(DictionaryConst.WhetherMaven.WHETHER_OK);
                                    supplierOrderFrightModelMapper.updateByPrimaryKeySelective(supplierOrderFrightModel);
                                }
                            } else {
                                if (otype.equals(DictionaryConst.OrdersType.ORDERS_HEADER_GM)){
                                    vo.setPrice(vo.getPrice().add(freight));
                                    realMoney = realMoney.add(freight);
                                }
                            }
                        } else {
                            //同商品不同规格的详单只会有一个详单会有运费 所以需要判断如果退款的是有运费的详单则会将运费保存在另外一个没运费的详单中去(用于结算 供应商订单除外因为供应商订单有单独的运费信息表)
                            if ((freight != null && freight.compareTo(BigDecimal.ZERO) > 0) && !isSupplierPro) {
                                OrderDetailsModel sameProOrderDetail = orderDetailsModelMapper.getSameProOrderDetail(vo.getStoreId(), orderno, goodsId, detailId);
                                if (sameProOrderDetail != null){
                                    sameProOrderDetail.setFreight(freight);
                                    orderDetailsModelMapper.updateByPrimaryKeySelective(sameProOrderDetail);
                                    OrderDetailsModel currentOrderDetail = orderDetailsModelMapper.selectByPrimaryKey(detailId);
                                    currentOrderDetail.setFreight(BigDecimal.ZERO);
                                    orderDetailsModelMapper.updateByPrimaryKeySelective(currentOrderDetail);
                                }
                            }
                        }
                        //收货后处理 收货后不管店铺输入多少退款金额,都按当前订单商品实际支付金额来。少退的会到可提现金额里面
                        if (isArruve) {
                            //店铺金额是否充足
                            if (vo.getPrice().compareTo(mchModel.getAccount_money()) > 0) {
                                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_TKSBDPYEBZ, "退款失败,店铺余额不足", "refund");
                            }

                            //增加店铺收入(运费)[可提现账户]
                            //运费不管发没发货都会退给用户 所以不需要入账
//                            if (BigDecimal.ZERO.compareTo(freight) < 0) {
//                                count = mchModelMapper.settlementMchCash(vo.getStoreId(), mchId, freight);
//                                if (count < 1) {
//                                    logger.info("[确认收货后]退款增加店铺收入失败(已发货结算运费) ");
//                                    throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_TKSB, "退款失败");
//                                }
//                                //运费入账
//                                mchAccountLogModel.setId(null);
//                                mchAccountLogModel.setPrice(freight);
//                                mchAccountLogModel.setRemake(orderno);
//                                mchAccountLogModel.setAccount_money(mchModel.getAccount_money());
//                                mchAccountLogModel.setType(DictionaryConst.MchAccountLogType.MCHACCOUNTLOG_TYPE_REFUND);
//                                mchAccountLogModel.setStatus(DictionaryConst.MchAccountLogStatus.MCHACCOUNTLOG_STATUS_INCOME);
//                                mchAccountLogModel.setAddtime(new Date());
//                                count = mchAccountLogModelMapper.insertSelective(mchAccountLogModel);
//                                if (count < 1) {
//                                    logger.info("退款记录失败(已发货结算运费) 参数:" + JSON.toJSONString(mchAccountLogModel));
//                                    throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_TKSBWLGZ, "退款失败,网络故障");
//                                }
//                            }
                            //计算店铺余额+运费(订单已完成,运费不退直接结算到店铺)
                            count = mchModelMapper.mchSettlement(mchModel.getId(), realMoney.negate());
                            if (count < 1) {
                                logger.info("退款失败 店铺{} 应退款{} 店铺应收入{}", mchModel.getId(), realMoney, 0);
                                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_TKSBWLGZ, "退款失败,网络故障", "refund");
                            }
                            //刷新店铺信息
                            mchModel = mchModelMapper.selectByPrimaryKey(mchModel.getId());
                            //添加一条退款记录
                            mchAccountLogModel.setId(null);
                            mchAccountLogModel.setPrice(vo.getPrice());
                            mchAccountLogModel.setAccount_money(mchModel.getAccount_money());
                            mchAccountLogModel.setRemake(orderno);
                            mchAccountLogModel.setType(DictionaryConst.MchAccountLogType.MCHACCOUNTLOG_TYPE_REFUND);
                            mchAccountLogModel.setStatus(DictionaryConst.MchAccountLogStatus.MCHACCOUNTLOG_STATUS_EXPENDITURE);
                            mchAccountLogModel.setAddtime(new Date());
                            count = mchAccountLogModelMapper.insertSelective(mchAccountLogModel);
                            if (count < 1) {
                                logger.info("退款记录失败 参数:" + JSON.toJSONString(mchAccountLogModel));
                                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_TKSBWLGZ, "退款失败,网络故障");
                            }
                            //该订单是否有冻结的积分,如果有则退还
//                            signRecordModelMapper.updateScoreType(orderno, SignRecordModel.ScoreType.INTEGRAL_REFUND_RETURN, SignRecordModel.ScoreType.INTEGRAL_FROZEN);

                            logger.debug("开始退还冻结积分");
                            User clientUser = userBaseMapper.selectByUserId(vo.getStoreId(), clientUserId);
                            AddScoreVo addScoreVo = new AddScoreVo();
                            addScoreVo.setType(SignRecordModel.ScoreType.INTEGRAL_REFUND_RETURN);
                            addScoreVo.setOrderNo(orderno);
                            addScoreVo.setUserId(clientUserId);
                            addScoreVo.setStoreId(vo.getStoreId());
                            addScoreVo.setScoreOld(clientUser.getScore());
                            addScoreVo.setScore(signRecordModelMapper.getScoreNumByType(orderno, SignRecordModel.ScoreType.INTEGRAL_FROZEN));
                            addScoreVo.setEvent("退还冻结积分");
                            publicIntegralService.addScore(addScoreVo);
                        } else {
                            //2023/08/03新需求:退款成功是不会给店铺和供应商退运费(发了货也不退) 需等到整比订单过了售后期才会结算运费
                            //是否已经发货,如果发货了则退运费
//                            if (rStatus >= OrderModel.ORDER_UNRECEIVE) {
//                                //标记该商品已经结算
//                                isSettlement = true;
//                                //刷新店铺信息
//                                mchModel = mchModelMapper.selectByPrimaryKey(mchModel.getId());
//                                //退款-少退的部分记录到账【入账】 这里记录的是店铺钱包,但是实际上到账是到可提现账户【这里最好记录可提现账户的流水】
//                                mchAccountLogModel.setId(null);
//                                mchAccountLogModel.setPrice(freight);
//                                mchAccountLogModel.setRemake(orderno);
//                                mchAccountLogModel.setAccount_money(mchModel.getAccount_money());
//                                mchAccountLogModel.setType(DictionaryConst.MchAccountLogType.MCHACCOUNTLOG_TYPE_REFUND);
//                                mchAccountLogModel.setStatus(DictionaryConst.MchAccountLogStatus.MCHACCOUNTLOG_STATUS_INCOME);
//                                mchAccountLogModel.setAddtime(new Date());
//                                count = mchAccountLogModelMapper.insertSelective(mchAccountLogModel);
//                                if (count < 1) {
//                                    logger.info("退款记录失败(已发货结算运费) 参数:" + JSON.toJSONString(mchAccountLogModel));
//                                    throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_TKSBWLGZ, "退款失败,网络故障");
//                                }
//                                //增加店铺收入[可提现账户]
//                                count = mchModelMapper.settlementMchCash(vo.getStoreId(), mchId, freight);
//                                if (count < 1) {
//                                    logger.info("退款增加店铺收入失败(已发货结算运费) ");
//                                    throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_TKSB, "退款失败");
//                                }
//                            }
                        }
                        count = orderModelMapper.updateOrderPrice(vo.getStoreId(), orderno, vo.getPrice(), freight, orderDetailPrice);
                        if (count < 1) {
                            logger.info(String.format("退款订单价格扣减失败 订单号:%s 扣减订单总金额:%s 扣减运费:%s 扣减订单总商品金额:%s", orderno, vo.getPrice(), freight, orderDetailPrice));
                            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLGZTKSB, "网络故障,退款失败", "refund");
                        }
                        //统一订单状态
                        publicOrderService.updateOrderState(vo.getStoreId(), orderno);
                        //退款流程
                        switch (payType) {
                            case DictionaryConst.OrderPayType.ORDERPAYTYPE_WALLET_PAY:
                                //钱包支付全额退款
                                publicMemberService.returnUserMoney(vo.getStoreId(), clientUserId, vo.getPrice(), detailId, false);
                                break;
                            case DictionaryConst.OrderPayType.ORDERPAYTYPE_ALIPAY:
                            case DictionaryConst.OrderPayType.ORDERPAYTYPE_ALIPAY_TMP:
                            case DictionaryConst.OrderPayType.ORDERPAYTYPE_PC_ALIPAY:
                            case DictionaryConst.OrderPayType.ORDERPAYTYPE_ALIPAY_MINIPAY:
                            case DictionaryConst.OrderPayType.ORDERPAYTYPE_ALIPAY_WAP:
                                //发起退款
                                Map<String, String> map = publicAlipayServiceImpl.refundOrder(vo.getStoreId(), orderId, payType, realOrderno, vo.getPrice(), upPaymentPrice);
                                String code = map.get("code");
                                if (DictionaryConst.AliApiCode.ALIPAY_ACQ_SELLER_BALANCE_NOT_ENOUGH.equals(code)) {
                                    //短信通知商家
                                    if (isSendNotice) {
                                        publiceService.sendSms(vo.getStoreId(), mchPhone, GloabConst.VcodeCategory.TYPE_NOTICE, vo.getType(), smsParmaMap);
                                    }
                                    throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_TKSB, "退款失败", "refund");
                                }
                                break;
                            case DictionaryConst.OrderPayType.ORDERPAYTYPE_APP_WECHAT:
                            case DictionaryConst.OrderPayType.ORDERPAYTYPE_MINI_WECHAT:
                            case DictionaryConst.OrderPayType.ORDERPAYTYPE_PC_WECHAT:
                            case DictionaryConst.OrderPayType.ORDERPAYTYPE_H5_WECHAT:
                            case DictionaryConst.OrderPayType.ORDERPAYTYPE_JSAPI_WECHAT:
                                //微信退款
                                logger.info("退款参数-{}-,", JSON.toJSONString(vo));
                                logger.info("退款参数orderId-{},", orderId);
                                logger.info("退款参数payType-{}-,", payType);
                                logger.info("退款参数realOrderno-{},", realOrderno);
                                map = publicWechatServiceImpl.refundOrder(vo.getStoreId(), orderId, payType, realOrderno, vo.getPrice(), upPaymentPrice);
//                                Map<String, Object> dividendRefundMap = publicWechatServiceImpl.dividendRefund(orderno);
//                                logger.info("#########微信分账回退######## {}", JSONObject.toJSONString(dividendRefundMap));
                                logger.info("#########退款返回##### {}", JSONObject.toJSONString(map));
                                break;
                            default:
                                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_ZFFSBCZ, "支付方式不存在", "refund");
                        }
                    }
                } else if (DictionaryConst.ReturnOrderStatus.RETURNORDERSTATUS_AGREE_REBACK_GOODS.equals(vo.getType())) {
                    tuiTitle = String.format("【%s】订单发货啦！", orderno);
                    tuiContext = "您购买的商品已经在赶去见您的路上啦！";
                    //添加一条快递数据
                    ReturnGoodsModel returnGoodsModel = new ReturnGoodsModel();
                    returnGoodsModel.setStore_id(vo.getStoreId());
                    returnGoodsModel.setName(clientUserName);
                    returnGoodsModel.setTel(clientUserPhon);
                    if (StringUtils.isEmpty(vo.getExpressId())) {
                        throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_KDGSBNWK, "快递公司不能为空");
                    }
                    //查询快递公司信息
                    ExpressModel expressModel = new ExpressModel();
                    expressModel.setId(vo.getExpressId());
                    expressModel.setRecycle(DictionaryConst.ProductRecycle.NOT_STATUS);
                    expressModel = expressModelMapper.selectOne(expressModel);
                    if (expressModel == null) {
                        throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLGSBCZ, "物流公司不存在");
                    }
                    if (StringUtils.isEmpty(vo.getCourierNum())) {
                        throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_KDDHBNWK, "快递单号不能为空");
                    }
                    returnGoodsModel.setExpress(expressModel.getKuaidi_name());
                    returnGoodsModel.setExpress_num(vo.getCourierNum());
                    returnGoodsModel.setUser_id(clientUserId);
                    returnGoodsModel.setOid(detailId + "");
                    returnGoodsModel.setRe_id(vo.getId());
                    returnGoodsModel.setAdd_data(new Date());
                    count = returnGoodsModelMapper.insertSelective(returnGoodsModel);
                    if (count < 1) {
                        logger.info("新增售后记录失败 参数:" + JSON.toJSONString(returnGoodsModel));
                        throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLGZTKSB, "网络故障,退款失败", "refund");
                    }
                    //修改明细物流信息
                    OrderDetailsModel updateOrderDetail = new OrderDetailsModel();
                    updateOrderDetail.setId(detailId);
                    updateOrderDetail.setExpress_id(expressModel.getId().toString());
                    updateOrderDetail.setCourier_num(returnGoodsModel.getExpress_num());
                    count = orderDetailsModelMapper.updateByPrimaryKeySelective(updateOrderDetail);
                    if (count < 1) {
                        logger.info("修改订单物流信息失败 参数:" + JSON.toJSONString(updateOrderDetail));
                        throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLGZTKSB, "网络故障,退款失败", "refund");
                    }
                    updateOrderDetail = orderDetailsModelMapper.selectByPrimaryKey(detailId);
                    //物流记录表
                    ExpressDeliveryModel expressDeliveryModel = new ExpressDeliveryModel();
                    expressDeliveryModel.setStore_id(vo.getStoreId());
                    expressDeliveryModel.setsNo(updateOrderDetail.getR_sNo());
                    expressDeliveryModel.setExpressId(expressModel.getId());
                    expressDeliveryModel.setCourierNum(returnGoodsModel.getExpress_num());
                    expressDeliveryModel.setOrderDetailsId(updateOrderDetail.getId());
                    expressDeliveryModel.setNum(updateOrderDetail.getNum());
                    expressDeliveryModel.setDeliverTime(new Date());
                    expressDeliveryModelMapper.insertSelective(expressDeliveryModel);
                    //记录
                    returnRecordSave.setCourier_num(vo.getCourierNum());
                    returnRecordSave.setExpress_id(vo.getExpressId());
                } else if (vo.getType().equals(DictionaryConst.ReturnOrderStatus.RETURNORDERSTATUS_QUICK_SUPPLIER_AGRESS)){
                    tuiTitle = "退货退款";
                    tuiContext = "您的退货退款申请已通过!";
                }else {
                    String text = vo.getText() + "";
                    if (StringUtils.isEmpty(text.trim())) {
                        throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_LYBNWK, "理由不能为空", "refund");
                    }
                    //0:审核中 2:拒绝(退货退款) 3:用户已快递 5：拒绝并退回商品 8:拒绝(退款)10:拒绝(售后)
                    tuiTitle = "退货/退款失败!";
                    tuiContext = String.format("您申请的退货/退款被拒绝!原因：%s", vo.getText());
                    //记录
                    returnRecordSave.setContent(vo.getText());
                }
                //修改售后状态
                ReturnOrderModel updateReturnOrder = new ReturnOrderModel();
                updateReturnOrder.setId(vo.getId());
                updateReturnOrder.setR_type(vo.getType());
                updateReturnOrder.setR_content(vo.getText());
                if (realMoney != null && realMoney.compareTo(BigDecimal.ZERO) > 0) {
                    //实际退款金额
                    updateReturnOrder.setReal_money(realMoney.floatValue());
                }
                updateReturnOrder.setAudit_time(new Date());

                count = returnOrderModelMapper.updateByPrimaryKeySelective(updateReturnOrder);
                if (count < 1) {
                    logger.info("订单售后状态失败 参数:" + JSON.toJSONString(updateReturnOrder));
                    throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLGZTKSB, "网络故障,退款失败", "refund");
                }
                //重新生成一条售后记录 每次操作都增加一条售后记录 add by trick 2023-02-24 10:29:02
                returnRecordSave.setUser_id(clientUserId);
                returnRecordSave.setStore_id(vo.getStoreId());
                returnRecordSave.setRe_type(reType);
                returnRecordSave.setR_type(vo.getType());
                returnRecordSave.setsNo(orderno);
                returnRecordSave.setP_id(refundId);
                returnRecordSave.setMoney(realMoney);
                returnRecordSave.setProduct_id(goodsId);
                returnRecordSave.setAttr_id(attributeId);
                returnRecordSave.setRe_time(new Date());
                count = returnRecordModelMapper.insertSelective(returnRecordSave);
                if (count < 1) {
                    logger.info("添加售后信息失败 参数:" + JSON.toJSONString(returnRecordSave));
                    throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLGZSHJLSB, "网络故障,售后记录失败", "returnData");
                }
                //TODO 【微信推送暂时不做】 发送微信小程序推送退款信息
                //站内推送退款信息
                systemMessageSave.setTitle(tuiTitle);
                systemMessageSave.setContent(tuiContext);
                systemMessageSave.setTime(new Date());
                systemMessageModelMapper.insertSelective(systemMessageSave);
            } else {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_SHDDBCZ, "售后订单不存在", "refund");
            }
            //最后再判断一下订单是否可以售后
            ReturnOrderModel returnOrderModelNew = returnOrderModelMapper.getReturnNewInfoByDetailId(orderDetailId);
            if (returnOrderModelNew == null) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_SHDDYCX, "售后订单已撤销", "refund");
            }
            return true;
        } catch (ClassCastException c) {
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_CSLXBZQ, "参数类型不正确", "refund");
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            logger.error("售后 异常", e);
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "refund");
        }finally {
            //删除重复操作标识
            redisUtil.del(GloabConst.RedisHeaderKey.REFUND_ORDER_KEY + storeId + "_" + id);
        }
    }
    @Override
    public boolean quickRefund(RefundVo vo) throws LaiKeAPIException {
        int id = vo.getId();
        int storeId = vo.getStoreId();
        try {
            Map<String, Object> parmaMap = new HashMap<>(16);
            parmaMap.put("store_id", vo.getStoreId());
            //店铺联系方式
            String mchPhone = "";
            //是否短信配置 ---> 禅道47551 测试说没有发送短信给商家的功能
            boolean isSendNotice = false;
            //防止连续点击造成多次退款 -并发处理
            if (redisUtil.incr(GloabConst.RedisHeaderKey.REFUND_ORDER_KEY + storeId + "_" + id, 1) > 1){
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_CFCZ, "重复操作", "refund");
            }
            //售后记录
            ReturnRecordModel returnRecordSave = new ReturnRecordModel();
            returnRecordSave.setStore_id(vo.getStoreId());
            int count = 0;
            //获取电商平台管理员信息
            CustomerModel customerModel = new CustomerModel();
            customerModel.setId(vo.getStoreId());
            customerModel.setRecycle(DictionaryConst.ProductRecycle.NOT_STATUS);
            customerModel = customerModelMapper.selectOne(customerModel);
            if (customerModel != null) {
                mchPhone = customerModel.getMobile();
            }
            Integer orderDetailId = null;
            //进入订单详情把未读状态改成已读状态，已读状态的状态不变
            parmaMap.put("id", vo.getOrderDetailId());
            List<Map<String, Object>> orderInfoList = returnOrderModelMapper.getReturnOrderQuickRefund(parmaMap);
            if (orderInfoList != null && orderInfoList.size() > 0) {
                Map<String, Object> returnOrderInfoMap = orderInfoList.get(0);
                //订单读取状态
                int read = StringUtils.stringParseInt(returnOrderInfoMap.get("readd") + "");
                //订单id
                int orderId = StringUtils.stringParseInt(returnOrderInfoMap.get("oId").toString());
                //订单id
                String orderno = returnOrderInfoMap.get("sNo").toString();
                //订单详情id
                int detailId = orderDetailId = StringUtils.stringParseInt(returnOrderInfoMap.get("detialId").toString());
                //订单金额
                BigDecimal orderPrice = new BigDecimal(returnOrderInfoMap.get("z_price").toString());
                //订单原始支付金额
                BigDecimal old_total = new BigDecimal(returnOrderInfoMap.get("old_total").toString());
                //单个商品的实际支付金额
                BigDecimal goodsPayPrice = getOrderPrice(vo.getStoreId(), detailId);
                //买家userid
                String clientUserId = returnOrderInfoMap.get("user_id").toString();
                returnRecordSave.setUser_id(clientUserId);
                //商品id
                int goodsId = StringUtils.stringParseInt(returnOrderInfoMap.get("goodsId").toString());
                //是否是该订单下最后一个同商品不同规格还未结算和关闭的的商品 用于判断是否退给用户运费
                List<OrderDetailsModel> orderDetailsForPro = orderDetailsModelMapper.getSameProDetailNotCloseAndSettlement(vo.getStoreId(), orderno, goodsId);
                //是否为供应商商品
                boolean isSupplierPro = false;
                ProductListModel proModel = productListModelMapper.selectByPrimaryKey(goodsId);
                if (StringUtils.isNotEmpty(proModel.getGongyingshang()) && !Objects.isNull(proModel.getSupplier_superior())) {
                    isSupplierPro = true;
                }
                //属性id
                int attributeId = StringUtils.stringParseInt(returnOrderInfoMap.get("attributeId").toString());
                //支付方式
                String payType = returnOrderInfoMap.get("pay").toString();
                //订单商品使用的优惠卷id
                String couponId = returnOrderInfoMap.get("detailCouponId") + "";
                //订单商品运费
                BigDecimal freight = new BigDecimal(returnOrderInfoMap.get("freight").toString());
                //支付流水号
                String realOrderno = MapUtils.getString(returnOrderInfoMap, "real_sno", "");
                //父订单id
                String psNo = MapUtils.getString(returnOrderInfoMap, "p_sNo");
                //调起支付支付金额
                BigDecimal upPaymentPrice = old_total;
                OrderModel orderModel = new OrderModel();
                orderModel.setsNo(orderno);
                orderModel = orderModelMapper.selectOne(orderModel);

                // 订单拆单过
                if (StringUtils.isNotEmpty(psNo)){
                    //根据调起支付所用订单号获取主订单号(未支付先拆单，子订单调起支付所用调起支付所用订单号和总订单相同)
                    String sNo = orderModelMapper.getOrderByRealSno(realOrderno);
                    logger.info("根据吊起支付订单号获取主订单号:{}", sNo);
                    if (StringUtils.isNotEmpty(sNo)){
                        orderModel = new OrderModel();
                        orderModel.setsNo(sNo);
                        orderModel = orderModelMapper.selectOne(orderModel);
                        upPaymentPrice = orderModel.getOld_total();
                    }
                }

                //订单商品总价
                BigDecimal orderDetailPrice = new BigDecimal(returnOrderInfoMap.get("p_price").toString());
                //商品数量
                BigDecimal goodsNeedNum = new BigDecimal(returnOrderInfoMap.get("num").toString());
                orderDetailPrice = orderDetailPrice.multiply(goodsNeedNum);

                if (read == 0) {
                    orderModel = new OrderModel();
                    orderModel.setId(orderId);
                    orderModel.setReadd(OrderModel.READ);
                    count = orderModelMapper.updateByPrimaryKeySelective(orderModel);
                    if (count < 1) {
                        logger.info("修改订单已读状态失败 参数:" + JSON.toJSONString(orderModel));
                    }
                }
                //站内推送消息
                String tuiTitle = "退货/退款成功!";
                String tuiContext = "您的退货/退款申请已通过!";
                SystemMessageModel systemMessageSave = new SystemMessageModel();
                systemMessageSave.setStore_id(vo.getStoreId());
                systemMessageSave.setSenderid("admin");
                systemMessageSave.setRecipientid(clientUserId);
                systemMessageSave.setTitle(tuiTitle);
                systemMessageSave.setContent(tuiContext);
                systemMessageSave.setType(SystemMessageModel.ReadType.UNREAD);

                //实际退款金额
                BigDecimal realMoney = vo.getPrice();
                //订单售后流程
                logger.info("===同意退款===");
                //获取实际支付金额
                logger.info("同意订单详情id{}退款,订单商品付款金额{},实际退款金额{}", detailId, goodsPayPrice, vo.getPrice());
                // 组合支付不要了
                if (DictionaryConst.OrderPayType.ORDERPAYTYPE_TT_ALIPAY.equals(payType)) {
                    payType = DictionaryConst.OrderPayType.ORDERPAYTYPE_ALIPAY;
                } else if (DictionaryConst.OrderPayType.ORDERPAYTYPE_BAIDU_PAY.equals(payType)) {
                    payType = DictionaryConst.OrderPayType.ORDERPAYTYPE_WALLET_PAY;
                }
                //获取短信列表
                Map<String, Object> messageInfo = messageListModelMapper.getMessageListInfoByType(vo.getStoreId(), GloabConst.VcodeCategory.TYPE_NOTICE, GloabConst.VcodeCategory.PAY_REFUND_ORDER);
                String content;
                String parmaJson;
                Map<String, String> smsParmaMap = null;
                if (messageInfo != null) {
                    isSendNotice = true;
                    content = messageInfo.get("content").toString();
                    parmaJson = JSON.toJSONString(SerializePhpUtils.getUnserializeObj(content, Map.class));
                    smsParmaMap = JSON.parseObject(parmaJson, new TypeReference<Map<String, String>>() {
                    });
                } else {
                    logger.error("商城【{}】未配置通知短信服务!", vo.getStoreId());
                }
                logger.info("退款信息payType，{}", payType);
                //获取商品库存信息
                ConfiGureModel confiGureModel = new ConfiGureModel();
                confiGureModel.setId(attributeId);
                confiGureModel = confiGureModelMapper.selectOne(confiGureModel);
                if (confiGureModel == null) {
                    throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_SPKCBCZ, "商品库存不存在", "refund");
                }
                //供应商商品处理
                Integer cid = confiGureModel.getId();
                Integer goodId = goodsId;
                if (isSupplierPro) {
                    //子供应商商品也需要回滚
                    count = productListModelMapper.updateProductListVolume(goodsNeedNum.negate().intValue(), vo.getStoreId(), goodId);
                    if (count < 1) {
                        logger.info("销量扣减失败 商品id:" + goodId + " 销量扣减数量:" + goodsNeedNum);
                        throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLGZTKSB, "网络故障,退款失败", "refund");
                    }
                    count = confiGureModelMapper.reduceGoodsStockNum(goodsNeedNum.negate().intValue(), cid);
                    if (count < 1) {
                        logger.info("回滚属性库存失败 商品id:" + goodId + " 退货数量:" + goodsNeedNum);
                        throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLGZTKSB, "网络故障,退款失败", "refund");
                    }
                    count = productListModelMapper.addGoodsStockNum(goodId, goodsNeedNum.intValue());
                    if (count < 1) {
                        logger.info("商品库存回滚失败 商品id:" + goodId + " 销量扣减数量:" + goodsNeedNum);
                        throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLGZTKSB, "网络故障,退款失败", "refund");
                    }
                    confiGureModel = confiGureModelMapper.selectByPrimaryKey(confiGureModel.getSupplier_superior());
                    cid = confiGureModel.getId();
                    goodId = proModel.getSupplier_superior();
                    logger.info("正在处理供应商商品id" + goodId + "----->规格id" + cid + "回滚库存、扣减销量、增加总库存操作");
                }
                //预售商品需要回滚所有规格库存
                if (proModel.getIs_presell().equals(DictionaryConst.WhetherMaven.WHETHER_OK)) {
                    count = confiGureModelMapper.reduceProAllAttrNum(goodsNeedNum.negate().intValue(), goodsId);
                    if (count < 1) {
                        logger.info("回滚属性库存失败 商品id:" + goodId + " 退货数量:" + goodsNeedNum);
                        throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLGZTKSB, "网络故障,退款失败", "refund");
                    }
                } else {
                    //回滚库存
                    count = confiGureModelMapper.reduceGoodsStockNum(goodsNeedNum.negate().intValue(), cid);
                    if (count < 1) {
                        logger.info("回滚属性库存失败 商品id:" + goodId + " 退货数量:" + goodsNeedNum);
                        throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLGZTKSB, "网络故障,退款失败", "refund");
                    }
                }
                //减销量
                count = productListModelMapper.updateProductListVolume(goodsNeedNum.negate().intValue(), vo.getStoreId(), goodId);
                if (count < 1) {
                    logger.info("销量扣减失败 商品id:" + goodId + " 销量扣减数量:" + goodsNeedNum);
                    throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLGZTKSB, "网络故障,退款失败", "refund");
                }
                // 增加商品库存
                count = productListModelMapper.addGoodsStockNum(goodId, goodsNeedNum.intValue());
                if (count < 1) {
                    logger.info("商品库存回滚失败 商品id:" + goodId + " 销量扣减数量:" + goodsNeedNum);
                    throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLGZTKSB, "网络故障,退款失败", "refund");
                }
                //退款成功 增加商品总库存
                String text = "退款成功,增加商品库存" + goodsNeedNum;
                StockModel stockModel = new StockModel();
                stockModel.setStore_id(vo.getStoreId());
                stockModel.setProduct_id(goodId);
                stockModel.setAttribute_id(cid);
                stockModel.setTotal_num(confiGureModel.getTotal_num());
                stockModel.setFlowing_num(goodsNeedNum.intValue());
                stockModel.setType(StockModel.StockType.STOCKTYPE_WAREHOUSING);
                stockModel.setContent(text);
                stockModel.setAdd_date(new Date());
                count = stockModelMapper.insertSelective(stockModel);
                if (count < 1) {
                    logger.info("添加商品库存失败 参数:" + JSON.toJSONString(stockModel));
                    throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLGZTKSB, "网络故障,退款失败", "refund");
                }
                //修改订单状态为关闭
                OrderDetailsModel orderDetailsModel = new OrderDetailsModel();
                orderDetailsModel.setId(detailId);
                orderDetailsModel.setR_status(DictionaryConst.OrdersStatus.ORDERS_R_STATUS_CLOSE);
                orderDetailsModel.setAudit_time(new Date());
                count = orderDetailsModelMapper.updateByPrimaryKeySelective(orderDetailsModel);
                if (count < 1) {
                    logger.info("关闭订单失败 参数:" + JSON.toJSONString(orderDetailsModel));
                    throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLGZTKSB, "网络故障,退款失败", "refund");
                }

                //如果订单商品使用了优惠卷
                if (!StringUtils.isEmpty(couponId)) {
                    if (!("0,0".equals(couponId) || "0".equals(couponId))) {
                        // 当订单详情使用了优惠券
                        // 订单详情使用的优惠券ID字符串 转数组
                        String[] couponList = couponId.split(SplitUtils.DH);
                        for (int i = 0; i < couponList.length; i++) {
                            String tmpCouponId = couponList[i];
                            if (!"0".equals(tmpCouponId) && null != tmpCouponId) {
                                // 使用了优惠券
                                if (i == 0 || (i == 1 && "".equals(psNo))) {
                                    // 使用了店铺优惠券 或 (使用了平台优惠券 并且 不是跨店铺订单)
                                    // 根据商城ID、订单号、店铺优惠券ID，查询不是这个订单详情的数据
                                    List<Map<String, Object>> otherOrders = orderDetailsModelMapper.getOrderDetailsUseTheCoupon(vo.getStoreId(), orderno, tmpCouponId, orderId);
                                    boolean flag = false;
                                    //所有详单的优惠和金额为0
                                    boolean allAfterDiscountIsZero = true;
                                    if (otherOrders != null && otherOrders.size() > 0) {
                                        // 存在(该订单里，还有其它详情使用了这张店铺优惠券)
                                        // 该订单里，有多少详情使用了这张店铺优惠券
                                        int size = otherOrders.size();
                                        // 该订单里，使用了这张店铺优惠券,并退款或退货退款成功的数量
                                        int returnNum = 0;
                                        for (Map<String, Object> otherOrderDetail : otherOrders) {
                                            int orderStatus = MapUtils.getIntValue(otherOrderDetail, "r_status");
                                            if (orderStatus == DictionaryConst.OrdersStatus.ORDERS_R_STATUS_CLOSE) {
                                                returnNum++;
                                            }
                                            //优惠后金额不为0
                                            if (BigDecimal.ZERO.compareTo(new BigDecimal(MapUtils.getString(otherOrderDetail, "after_discount"))) != 0){
                                                allAfterDiscountIsZero = false;
                                            }
                                        }
                                        if (returnNum == size) {
                                            flag = true;
                                        }
                                    } else {
                                        flag = true;
                                    }
                                    if (flag) {
                                        // 该订单，使用了这张店铺优惠券的订单商品都退款或退款退款成功
                                        int row = publicCouponService.couponWithOrder(vo.getStoreId(), clientUserId, tmpCouponId, orderno, "update");
                                        if (row == 0) {
                                            //回滚删除已经创建的订单
                                            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLGZTKSB, "网络故障,退款失败", "refund");
                                        }
                                        // =2
                                        row = publicCouponService.updateCoupons(vo.getStoreId(), clientUserId, tmpCouponId, CouponModal.COUPON_TYPE_NOT_USED);
                                        if (row == 0) {
                                            //回滚删除已经创建的订单
                                            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLGZTKSB, "网络故障,退款失败", "refund");
                                        }
                                        //使用了平台优惠卷，优惠金额大于总价。当订单所有商品退款成功时须将支付的0.01元退还 2023-09-12 gp
                                        if (i == 1 && allAfterDiscountIsZero && orderPrice.compareTo(new BigDecimal("0.01")) == 0){
                                            vo.setPrice(vo.getPrice().add(orderPrice));
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                //判断是否为预售商品，修改预售订单表的数据
                PreSellRecordModel preSellRecordModel = new PreSellRecordModel();
                preSellRecordModel.setsNo(orderno);
                List<PreSellRecordModel> select = preSellRecordModelMapper.select(preSellRecordModel);
                if (!Objects.isNull(select) && select.size() > 0) {
                    for (PreSellRecordModel model : select){
                        model.setIs_refund(1);
                        preSellRecordModelMapper.updateByPrimaryKeySelective(model);
                    }
                }
                //如果是退款详单是该订单下同商品不同规格最后一个商品则会退给用户运费 反之则不退
                if (orderDetailsForPro.size() == 1) {
                    //供应商商品运费逻辑处理 如果为订单中最后一个同商品不同规格的数据进行退款 则供应商运费数据标记已结算
                    if (isSupplierPro) {
                        SupplierOrderFrightModel supplierOrderFrightModel = new SupplierOrderFrightModel();
                        supplierOrderFrightModel.setStore_id(vo.getStoreId());
                        supplierOrderFrightModel.setsNo(orderno);
                        supplierOrderFrightModel.setDetail_id(goodsId);
                        supplierOrderFrightModel = supplierOrderFrightModelMapper.selectOne(supplierOrderFrightModel);
                        if (supplierOrderFrightModel != null) {
                            vo.setPrice(vo.getPrice().add(supplierOrderFrightModel.getFreight()));
                            realMoney = realMoney.add(supplierOrderFrightModel.getFreight());
                            supplierOrderFrightModel.setFreight(BigDecimal.ZERO);
                            supplierOrderFrightModel.setIs_settlement(DictionaryConst.WhetherMaven.WHETHER_OK);
                            supplierOrderFrightModelMapper.updateByPrimaryKeySelective(supplierOrderFrightModel);
                        }
                    } else {
                        vo.setPrice(vo.getPrice().add(freight));
                        realMoney = realMoney.add(freight);
                    }
                } else {
                    //同商品不同规格的详单只会有一个详单会有运费 所以需要判断如果退款的是有运费的详单则会将运费保存在另外一个没运费的详单中去(用于结算 供应商订单除外因为供应商订单有单独的运费信息表)
                    if ((freight != null && freight.compareTo(BigDecimal.ZERO) > 0) && !isSupplierPro) {
                        OrderDetailsModel sameProOrderDetail = orderDetailsModelMapper.getSameProOrderDetail(vo.getStoreId(), orderno, goodsId, detailId);
                        if (sameProOrderDetail != null){
                            sameProOrderDetail.setFreight(freight);
                            orderDetailsModelMapper.updateByPrimaryKeySelective(sameProOrderDetail);
                            OrderDetailsModel currentOrderDetail = orderDetailsModelMapper.selectByPrimaryKey(detailId);
                            currentOrderDetail.setFreight(BigDecimal.ZERO);
                            orderDetailsModelMapper.updateByPrimaryKeySelective(currentOrderDetail);
                        }
                    }
                }
                count = orderModelMapper.updateOrderPrice(vo.getStoreId(), orderno, vo.getPrice(), freight, orderDetailPrice);
                if (count < 1) {
                    logger.info(String.format("退款订单价格扣减失败 订单号:%s 扣减订单总金额:%s 扣减运费:%s 扣减订单总商品金额:%s", orderno, vo.getPrice(), freight, orderDetailPrice));
                    throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLGZTKSB, "网络故障,退款失败", "refund");
                }
                //统一订单状态
                publicOrderService.updateOrderState(vo.getStoreId(), orderno);
                //退款流程
                switch (payType) {
                    case DictionaryConst.OrderPayType.ORDERPAYTYPE_WALLET_PAY:
                        //钱包支付全额退款
                        publicMemberService.returnUserMoney(vo.getStoreId(), clientUserId, vo.getPrice(), detailId, false);
                        break;
                    case DictionaryConst.OrderPayType.ORDERPAYTYPE_ALIPAY:
                    case DictionaryConst.OrderPayType.ORDERPAYTYPE_ALIPAY_TMP:
                    case DictionaryConst.OrderPayType.ORDERPAYTYPE_PC_ALIPAY:
                    case DictionaryConst.OrderPayType.ORDERPAYTYPE_ALIPAY_MINIPAY:
                    case DictionaryConst.OrderPayType.ORDERPAYTYPE_ALIPAY_WAP:
                        //发起退款
                        Map<String, String> map = publicAlipayServiceImpl.refundOrder(vo.getStoreId(), orderId, payType, realOrderno, vo.getPrice(), upPaymentPrice);
                        String code = map.get("code");
                        if (DictionaryConst.AliApiCode.ALIPAY_ACQ_SELLER_BALANCE_NOT_ENOUGH.equals(code)) {
                            //短信通知商家
                            if (isSendNotice) {
                                publiceService.sendSms(vo.getStoreId(), mchPhone, GloabConst.VcodeCategory.TYPE_NOTICE, vo.getType(), smsParmaMap);
                            }
                            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_TKSB, "退款失败", "refund");
                        }
                        break;
                    case DictionaryConst.OrderPayType.ORDERPAYTYPE_APP_WECHAT:
                    case DictionaryConst.OrderPayType.ORDERPAYTYPE_MINI_WECHAT:
                    case DictionaryConst.OrderPayType.ORDERPAYTYPE_PC_WECHAT:
                    case DictionaryConst.OrderPayType.ORDERPAYTYPE_H5_WECHAT:
                    case DictionaryConst.OrderPayType.ORDERPAYTYPE_JSAPI_WECHAT:
                        //微信退款
                        logger.info("退款参数-{}-,", JSON.toJSONString(vo));
                        logger.info("退款参数orderId-{},", orderId);
                        logger.info("退款参数payType-{}-,", payType);
                        logger.info("退款参数realOrderno-{},", realOrderno);
                        map = publicWechatServiceImpl.refundOrder(vo.getStoreId(), orderId, payType, realOrderno, vo.getPrice(), upPaymentPrice);
//                        Map<String, Object> dividendRefundMap = publicWechatServiceImpl.dividendRefund(orderno);
//                        logger.info("#########微信分账回退######## {}", JSONObject.toJSONString(dividendRefundMap));
                        logger.info("#########退款返回##### {}", JSONObject.toJSONString(map));
                        break;
                    default:
                        throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_ZFFSBCZ, "支付方式不存在", "refund");
                }
                //修改售后状态
                ReturnOrderModel updateReturnOrder = new ReturnOrderModel();
                updateReturnOrder.setId(vo.getId());
                updateReturnOrder.setR_type(vo.getType());
                updateReturnOrder.setR_content(vo.getText());
                if (realMoney.compareTo(BigDecimal.ZERO) > 0) {
                    //实际退款金额
                    updateReturnOrder.setReal_money(realMoney.floatValue());
                }
                updateReturnOrder.setAudit_time(new Date());
                count = returnOrderModelMapper.updateByPrimaryKeySelective(updateReturnOrder);
                if (count < 1) {
                    logger.info("订单售后状态失败 参数:" + JSON.toJSONString(updateReturnOrder));
                    throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLGZTKSB, "网络故障,退款失败", "refund");
                }
                //重新生成一条售后记录 每次操作都增加一条售后记录 add by trick 2023-02-24 10:29:02
                returnRecordSave.setUser_id(clientUserId);
                returnRecordSave.setStore_id(vo.getStoreId());
                returnRecordSave.setRe_type(vo.getReType());
                returnRecordSave.setR_type(vo.getType());
                returnRecordSave.setsNo(orderno);
                returnRecordSave.setP_id(vo.getId());
                returnRecordSave.setMoney(realMoney);
                returnRecordSave.setProduct_id(goodsId);
                returnRecordSave.setAttr_id(attributeId);
                returnRecordSave.setRe_time(new Date());
                count = returnRecordModelMapper.insertSelective(returnRecordSave);
                if (count < 1) {
                    logger.info("添加售后信息失败 参数:" + JSON.toJSONString(returnRecordSave));
                    throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLGZSHJLSB, "网络故障,售后记录失败", "returnData");
                }
                //TODO 【微信推送暂时不做】 发送微信小程序推送退款信息
                //站内推送退款信息
                systemMessageSave.setTitle(tuiTitle);
                systemMessageSave.setContent(tuiContext);
                systemMessageSave.setTime(new Date());
                systemMessageModelMapper.insertSelective(systemMessageSave);
            } else {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_SHDDBCZ, "售后订单不存在", "refund");
            }
            //最后再判断一下订单是否可以售后
            ReturnOrderModel returnOrderModelNew = returnOrderModelMapper.getReturnNewInfoByDetailId(orderDetailId);
            if (returnOrderModelNew == null) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_SHDDYCX, "售后订单已撤销", "refund");
            }
            return true;
        } catch (ClassCastException c) {
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_CSLXBZQ, "参数类型不正确", "refund");
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            logger.error("售后 异常", e);
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "refund");
        }finally {
            //删除重复操作标识
            redisUtil.del(GloabConst.RedisHeaderKey.REFUND_ORDER_KEY + storeId + "_" + id);
        }
    }
    @Override
    public Map<String, Object> refundPageById(int storeId, int id) throws LaiKeAPIException {
        Map<String, Object> resultMap = new HashMap<>(16);
        try {
            //获取售后订单细信息
            Map<String, Object> refundInfoMap = returnOrderModelMapper.getReturnOrderMap(storeId, id, null);
            if (refundInfoMap != null && !refundInfoMap.isEmpty()) {
                //商品id
                int pid = Integer.parseInt(refundInfoMap.get("goodsId").toString());
                refundInfoMap.put("pid", pid);
                //订单详情id
                int orderDetailId = Integer.parseInt(refundInfoMap.get("p_id").toString());
                //售后处理状态
                int rtype = Integer.parseInt(refundInfoMap.get("rtype").toString());
                int reType = MapUtils.getIntValue(refundInfoMap, "re_type");
                //订单号
                String orderno = refundInfoMap.get("sNo").toString();


                //获取商品信息
                ProductListModel productListModel = new ProductListModel();
                productListModel.setId(pid);
                productListModel = productListModelMapper.selectOne(productListModel);
                if (productListModel == null) {
                    throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_SPBCZ, "商品不存在", "refundPageById");
                }
                String imgUrl = publiceService.getImgPath(productListModel.getImgurl(), storeId);
                refundInfoMap.put("imgurl", imgUrl);

                //商品金额
                BigDecimal goodsPrice = new BigDecimal(refundInfoMap.get("p_price").toString());
                //实付金额
                BigDecimal paidPrice = new BigDecimal(refundInfoMap.get("after_discount").toString());
                //数量
                BigDecimal needNum = new BigDecimal(refundInfoMap.get("num").toString());
                //运费
                BigDecimal yunfei = new BigDecimal(refundInfoMap.get("freight").toString());
                //小计
                BigDecimal subtotal = goodsPrice.multiply(needNum).add(yunfei);
                //合计
                BigDecimal total = paidPrice.add(yunfei);
                //优惠金额 ==小计 - 合计
                BigDecimal discountAmount = subtotal.subtract(total);
                refundInfoMap.put("z_price", subtotal);
                refundInfoMap.put("total", total);
                refundInfoMap.put("discountAmount", discountAmount);

                //获取售后凭证图
                List<String> rePhotoImgUrlList = new ArrayList<>();
                String rePhoto = String.valueOf(refundInfoMap.get("re_photo"));
                Map<Integer, String> rePhotoMap = DataUtils.cast(SerializePhpUtils.getUnserializeObj(rePhoto, Map.class));
                if (rePhotoMap != null) {
                    for (Integer key : rePhotoMap.keySet()) {
                        String photoImgUrl = rePhotoMap.get(key);
                        photoImgUrl = publiceService.getImgPath(photoImgUrl, storeId);
                        rePhotoImgUrlList.add(photoImgUrl);
                    }
                }

                //region 显示回寄物流信息
                List<ReturnGoodsModel> returnGoodsModelList = null;
                ReturnGoodsModel returnGoodsModel = new ReturnGoodsModel();
                returnGoodsModel.setStore_id(storeId);
                returnGoodsModel.setOid(String.valueOf(orderDetailId));
                returnGoodsModel.setRe_id(id);
                returnGoodsModelList = returnGoodsModelMapper.select(returnGoodsModel);
                //endregion

                //标记已读
                orderModelMapper.updateIsReadd(storeId, orderno, OrderModel.READ);

                //查询售后记录
                List<RefundResultView> refundResultViewList = new ArrayList<>();
                List<ReturnRecordModel> returnRecordModels = returnRecordModelMapper.getReturnRecord(storeId, id);
                for (ReturnRecordModel recordModel : returnRecordModels) {
                    //视图参数
                    RefundResultView refundResultView = new RefundResultView();
                    //审核结果
                    String examineResultStr = "";
                    //拒绝原因
                    String refuseText = "";
                    int rTypeOld = recordModel.getR_type();
                    int reTypeOld = recordModel.getRe_type();
                    if (rTypeOld == 0) {
                        examineResultStr = "审核中";
                        refundResultView.setApplyTime(DateUtil.dateFormate(recordModel.getRe_time(), GloabConst.TimePattern.YMDHMS));
                        recordModel.setRe_time(null);
                    } else if (rTypeOld == DictionaryConst.ReturnOrderStatus.RETURNORDERSTATUS_RECEIVED_REBAKGOODS
                            || rTypeOld == DictionaryConst.ReturnOrderStatus.RETURNORDERSTATUS_AGREE_REBACK_AMT
                            || rTypeOld == DictionaryConst.ReturnOrderStatus.RETURNORDERSTATUS_REFUSE_ARTIFICIAL_OK) {
                        examineResultStr = "退款成功";
                        refundResultView.setReturnMoney(recordModel.getMoney());
                    }  else if( rTypeOld == DictionaryConst.ReturnOrderStatus.RETURNORDERSTATUS_QUICK_REFUND) {
                        //(系统自动审核)
                        examineResultStr = "退款成功";
                        refundResultView.setReturnMoney(recordModel.getMoney());
                    }else {
                        if (rTypeOld == DictionaryConst.ReturnOrderStatus.RETURNORDERSTATUS_REFUSE_REBACKGOODS_AMT
                                || rTypeOld == DictionaryConst.ReturnOrderStatus.RETURNORDERSTATUS_REFUSE_AFTER_SALE
                                || rTypeOld == DictionaryConst.ReturnOrderStatus.RETURNORDERSTATUS_REFUSE_REBACKGOODS
                                || rTypeOld == DictionaryConst.ReturnOrderStatus.RETURNORDERSTATUS_REFUSE_AMT) {
                            examineResultStr = "审核拒绝";
                            refuseText = recordModel.getContent();
                        } else if (rTypeOld == DictionaryConst.ReturnOrderStatus.RETURNORDERSTATUS_USER_DELIVERED) {
                            examineResultStr = "商品审核中";
                            ExpressModel expressModel = expressModelMapper.selectByPrimaryKey(recordModel.getExpress_id());
                            String str = "-";
                            if (expressModel != null) {
                                str = expressModel.getKuaidi_name();
                            }
                            refundResultView.setReBackNo(String.format("%s(%s)", recordModel.getCourier_num(), str));
                            refundResultView.setReBackTime(DateUtil.dateFormate(recordModel.getRe_time(), GloabConst.TimePattern.YMDHMS));
                            recordModel.setRe_time(null);
                        } else if (rTypeOld == DictionaryConst.ReturnOrderStatus.RETURNORDERSTATUS_AGREE_REBACK
                                || rTypeOld == DictionaryConst.ReturnOrderStatus.RETURNORDERSTATUS_QUICK_SUPPLIER_AGRESS) {
                            examineResultStr = "审核通过";
                        } else if (rTypeOld == DictionaryConst.ReturnOrderStatus.RETURNORDERSTATUS_AGREE_REBACK_GOODS) {
                            examineResultStr = "商品审核通过";
                            ExpressModel expressModel = expressModelMapper.selectByPrimaryKey(recordModel.getExpress_id());
                            String str = "-";
                            if (expressModel != null) {
                                str = expressModel.getKuaidi_name();
                            }
                            refundResultView.setReturnBackNo(String.format("%s(%s)", recordModel.getCourier_num(), str));
                            refundResultView.setReBackTime(DateUtil.dateFormate(recordModel.getRe_time(), GloabConst.TimePattern.YMDHMS));
                        }
                    }
                    if (recordModel.getRe_time() != null) {
                        refundResultView.setExamineResultTime(DateUtil.dateFormate(recordModel.getRe_time(), GloabConst.TimePattern.YMDHMS));
                    }
                    refundResultView.setExamineResult(examineResultStr);
                    refundResultView.setRefuseText(refuseText);

                    if (StringUtils.isNotEmpty(examineResultStr)) {
                        refundResultViewList.add(refundResultView);
                    }
                }

                //用户退货记录信息
                resultMap.put("rdata", returnGoodsModelList);
                //售后记录
                resultMap.put("examineInfo", refundResultViewList);
                //售后记录信息
                resultMap.put("record", returnRecordModels);
                //售后订单细信息
                resultMap.put("list", refundInfoMap);
                //售后凭证信息
                resultMap.put("imgs", rePhotoImgUrlList);
            }
        } catch (Exception e) {
            logger.error("根据id查询售后信息 异常", e);
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "getBrandInfo");
        }
        return resultMap;
    }

    @Override
    public String getRefundStatus(int storeId, int detailId) throws LaiKeAPIException {
        String statusName;
        try {
            if (detailId == 0) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_XQBNWK, "详情id不能为空");
            }
            //查询售后情况
            ReturnOrderModel returnOrderModel = returnOrderModelMapper.getReturnNewInfoByDetailId(detailId);
            statusName = getRefundStatusByName(returnOrderModel);
        } catch (Exception e) {
            logger.error("获取售后状态【订单商品】 异常", e);
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "getRefundStatus");
        }
        return statusName;
    }

    @Override
    public String getRefundStatus(int storeId, Integer recId) throws LaiKeAPIException {
        try {
            if (recId == null) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_CSCW, "参数错误");
            }
            ReturnOrderModel returnOrderModel = returnOrderModelMapper.selectByPrimaryKey(recId);
            return getRefundStatusByName(returnOrderModel);
        } catch (LaiKeAPIException l) {
            throw l;
        }
    }

    @Override
    public String getRefundStatus(int storeId, String orderNo) throws LaiKeAPIException {
        try {
            return getRefundStatus(storeId, orderNo, null);
        } catch (Exception e) {
            logger.error("获取售后状态【订单】 异常" + e);
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "getRefundStatus");
        }
    }

    @Override
    public String getRefundStatus(int storeId, String orderNo, Integer orderDetailId) throws LaiKeAPIException {
        String statusName;
        try {
            if (StringUtils.isEmpty(orderNo)) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_DDHBNWK, "订单号不能为空");
            }
            //查询售后情况
            ReturnOrderModel returnOrderModel;
            if (orderDetailId == null) {
                returnOrderModel = returnOrderModelMapper.getReturnNewInfoBySno(orderNo);
            } else {
                returnOrderModel = returnOrderModelMapper.getReturnNewInfoByDetailId(orderDetailId);
            }
            statusName = getRefundStatusByName(returnOrderModel);
        } catch (Exception e) {
            logger.error("获取售后状态【订单】 异常" + e);
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "getRefundStatus");
        }
        return statusName;
    }

    private String getRefundStatusByName(ReturnOrderModel returnOrderModel) {
        String statusName = "";
        if (returnOrderModel != null) {
            int rType = returnOrderModel.getR_type();
            int reType = returnOrderModel.getRe_type();

            //退款转态
            if (reType == DictionaryConst.ReturnRecordReType.RETURNORDERTYPE_REFUSE_AMT
                    && rType == DictionaryConst.ReturnOrderStatus.RETURNORDERSTATUS_EXAMEWAIT_STATUS) {
                statusName = "审核中";
            } else if (rType == DictionaryConst.ReturnOrderStatus.RETURNORDERSTATUS_RECEIVED_REBAKGOODS
                    || rType == DictionaryConst.ReturnOrderStatus.RETURNORDERSTATUS_AGREE_REBACK_AMT
                    || rType == DictionaryConst.ReturnOrderStatus.RETURNORDERSTATUS_REFUSE_ARTIFICIAL_OK
                    || rType == DictionaryConst.ReturnOrderStatus.RETURNORDERSTATUS_QUICK_REFUND) {
                statusName = "退款成功";
            } else if (reType != DictionaryConst.ReturnRecordReType.RETURNORDERSTATUS_GOODS_REBACK
                    && (rType == DictionaryConst.ReturnOrderStatus.RETURNORDERSTATUS_REFUSE_REBACKGOODS_AMT || rType == DictionaryConst.ReturnOrderStatus.RETURNORDERSTATUS_REFUSE_REBACKGOODS || rType == DictionaryConst.ReturnOrderStatus.RETURNORDERSTATUS_REFUSE_AMT || rType == DictionaryConst.ReturnOrderStatus.RETURNORDERSTATUS_REFUSE_AFTER_SALE)) {
                statusName = "退款失败";
            } else if (reType == DictionaryConst.ReturnRecordReType.RETURNORDERSTATUS_GOODS_REBACK
                    && (rType == DictionaryConst.ReturnOrderStatus.RETURNORDERSTATUS_AGREE_REBACK || rType == DictionaryConst.ReturnOrderStatus.RETURNORDERSTATUS_USER_DELIVERED || rType == DictionaryConst.ReturnOrderStatus.RETURNORDERSTATUS_AGREE_REBACK_GOODS)) {
                statusName = "退换中";
            } else if (rType == DictionaryConst.ReturnOrderStatus.RETURNORDERSTATUS_AFTER_SALE_END) {
                statusName = "换货成功";
            } else if (reType == DictionaryConst.ReturnRecordReType.RETURNORDERSTATUS_GOODS_REBACK
                    && (rType == DictionaryConst.ReturnOrderStatus.RETURNORDERSTATUS_REFUSE_REBACKGOODS || rType == DictionaryConst.ReturnOrderStatus.RETURNORDERSTATUS_REFUSE_AFTER_SALE)) {
                statusName = "换货失败";
            } else if (reType == DictionaryConst.ReturnRecordReType.RETURNORDERSTATUS_REFUSE_REBACKGOODS_AMT && rType == DictionaryConst.ReturnOrderStatus.RETURNORDERSTATUS_AGREE_REBACK) {
                statusName = "退款中";
            } else {
                statusName = "审核中";
            }
        }
        return statusName;
    }

    @Override
    public int getOrderRefundType(int rType, int reType) throws LaiKeAPIException {
        //0=可以人工审核 1=待审核 2=退款中 3=退款成功 4=退款失败(仅退款) 5=退换中 6=换货成功 7=换货失败 8=退款失败(退货退款) 9=人工审核失败 10=人工审核成功
        int refundType = 0;
        //退款转态
        if (rType == 0) {
            refundType = 1;
        } else if (reType == DictionaryConst.ReturnRecordReType.RETURNORDERTYPE_REFUSE_AMT
                && (rType == DictionaryConst.ReturnOrderStatus.RETURNORDERSTATUS_AGREE_REBACK || rType == DictionaryConst.ReturnOrderStatus.RETURNORDERSTATUS_USER_DELIVERED)) {
            refundType = 2;
        } else if (rType == DictionaryConst.ReturnOrderStatus.RETURNORDERSTATUS_RECEIVED_REBAKGOODS || rType == DictionaryConst.ReturnOrderStatus.RETURNORDERSTATUS_AGREE_REBACK_AMT) {
            refundType = 3;
        } else if (reType != DictionaryConst.ReturnRecordReType.RETURNORDERSTATUS_GOODS_REBACK
                && (rType == DictionaryConst.ReturnOrderStatus.RETURNORDERSTATUS_REFUSE_REBACKGOODS_AMT || rType == DictionaryConst.ReturnOrderStatus.RETURNORDERSTATUS_REFUSE_REBACKGOODS
                || rType == DictionaryConst.ReturnOrderStatus.RETURNORDERSTATUS_REFUSE_AMT
                || rType == DictionaryConst.ReturnOrderStatus.RETURNORDERSTATUS_REFUSE_ARTIFICIAL_OK)) {
            //退款失败
            refundType = 4;
            if (reType == DictionaryConst.ReturnRecordReType.RETURNORDERSTATUS_REFUSE_REBACKGOODS_AMT) {
                refundType = 8;
            }
            //是否可以人工审核 只有用户回寄给商城之后才能人工审核
            if (rType == DictionaryConst.ReturnOrderStatus.RETURNORDERSTATUS_REFUSE_REBACKGOODS_AMT) {
                refundType = 0;
            }
            //是否人工审核
            if (rType == DictionaryConst.ReturnOrderStatus.RETURNORDERSTATUS_REFUSE_ARTIFICIAL_OK) {
                refundType = 10;
            }
        } else if (reType == DictionaryConst.ReturnRecordReType.RETURNORDERSTATUS_GOODS_REBACK
                && (rType == DictionaryConst.ReturnOrderStatus.RETURNORDERSTATUS_AGREE_REBACK || rType == DictionaryConst.ReturnOrderStatus.RETURNORDERSTATUS_USER_DELIVERED || rType == DictionaryConst.ReturnOrderStatus.RETURNORDERSTATUS_AGREE_REBACK_GOODS)) {
            refundType = 5;
        } else if (rType == DictionaryConst.ReturnOrderStatus.RETURNORDERSTATUS_AFTER_SALE_END) {
            refundType = 6;
        } else if (reType == DictionaryConst.ReturnRecordReType.RETURNORDERSTATUS_GOODS_REBACK
                && (rType == DictionaryConst.ReturnOrderStatus.RETURNORDERSTATUS_REFUSE_REBACKGOODS || rType == DictionaryConst.ReturnOrderStatus.RETURNORDERSTATUS_REFUSE_AFTER_SALE)) {
            refundType = 7;
            //是否人工审核
            if (rType == DictionaryConst.ReturnOrderStatus.RETURNORDERSTATUS_REFUSE_ARTIFICIAL_OK) {
                refundType = 10;
            }
        }
        return refundType;
    }

    @Override
    public boolean isExamine(int storeId, Integer refundId) throws LaiKeAPIException {
        boolean isExamine = false;
        ReturnOrderModel returnOrderOld = returnOrderModelMapper.selectByPrimaryKey(refundId);
        if (returnOrderOld == null) {
            return false;
        }
        if (DictionaryConst.ReturnOrderStatus.RETURNORDERSTATUS_EXAMEWAIT_STATUS.equals(returnOrderOld.getR_type())
                || DictionaryConst.ReturnOrderStatus.RETURNORDERSTATUS_USER_DELIVERED.equals(returnOrderOld.getR_type())
                || DictionaryConst.ReturnOrderStatus.RETURNORDERSTATUS_QUICK_SUPPLIER_AGRESS.equals(returnOrderOld.getR_type())
        ) {
            isExamine = true;
        }
        return isExamine;
    }

    @Override
    public boolean isMainExamine(int storeId, Integer refundId) throws LaiKeAPIException {
        boolean isManExamine = false;
        ReturnOrderModel returnOrderOld = returnOrderModelMapper.selectByPrimaryKey(refundId);
        if (returnOrderOld == null) {
            return false;
        }
        //商品回寄后被拒绝
        if (DictionaryConst.ReturnOrderStatus.RETURNORDERSTATUS_REFUSE_REBACKGOODS.equals(returnOrderOld.getR_type())) {
            isManExamine = true;
        }
        return isManExamine;
    }

    /**
     * 获取订单实际支付金额
     * 【php tool.get_order_price】
     *
     * @param id - 订单明细id
     * @return BigDecimal
     * @throws LaiKeAPIException -
     * @author Trick
     * @date 2020/12/2 15:33
     */
    private BigDecimal getOrderPrice(int storeId, int id) throws LaiKeAPIException {
        try {
            BigDecimal orderPrice;
            Map<String, Object> parmaMap = new HashMap<>(16);
            parmaMap.put("store_id", storeId);
            parmaMap.put("detailId", id);
            //获取商品信息
            List<Map<String, Object>> orderGoodsInfoList = orderModelMapper.getOrderInfoLeftDetailDynamic(parmaMap);
            if (orderGoodsInfoList != null && orderGoodsInfoList.size() > 0) {
                Map<String, Object> map = orderGoodsInfoList.get(0);
                //快递id
                int expressId = StringUtils.stringParseInt(map.get("express_id") + "");
                //运费
                BigDecimal freight = new BigDecimal(map.get("freight").toString());
                //订单号
                String sNo = map.get("sNo").toString();
                //商品id
                Integer pid = MapUtils.getInteger(map, "p_id");
                //判断是否存在供应商商品运费 有则替换
                SupplierOrderFrightModel supplierOrderFrightModel = new SupplierOrderFrightModel();
                supplierOrderFrightModel.setStore_id(storeId);
                supplierOrderFrightModel.setsNo(sNo);
                supplierOrderFrightModel.setDetail_id(pid);
                supplierOrderFrightModel = supplierOrderFrightModelMapper.selectOne(supplierOrderFrightModel);
                if (supplierOrderFrightModel != null){
                    freight = supplierOrderFrightModel.getTotal_fright();
                }
                //商品优惠后的实际金额
                BigDecimal afterDiscount = BigDecimal.ZERO;
                if (map.get("after_discount") != null) {
                    afterDiscount = new BigDecimal(map.get("after_discount").toString());
                }

                //判断是否发货
                if (freight.doubleValue() > 0 && expressId > 0) {
                    //发了货不退运费
                    orderPrice = afterDiscount;
                } else {
                    //计算实际支付金额
                    if (sNo.contains(DictionaryConst.OrdersType.ORDERS_HEADER_GM)){
                        orderPrice = afterDiscount;
                    }else {
                        orderPrice = afterDiscount.add(freight);
                    }
                }

                return orderPrice;
            } else {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WZDDDXX, "未找到订单信息", "getOrderPrice");
            }
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            logger.error("获取订单实际支付金额 异常", e);
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "getOrderPrice");
        }
    }

    @Override
    public Map<String, Boolean> afterSaleButtonShow(int storeId, String oType, OrderDetailsModel orderDetailsModel) throws LaiKeAPIException {
        Map<String, Boolean> resultMap = new HashMap<>(16);
        try {
            OrderModel orderModel = new OrderModel();
            orderModel.setsNo(orderDetailsModel.getR_sNo());
            orderModel = orderModelMapper.selectOne(orderModel);
            if (orderModel == null) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_DDBCZ, "订单不存在");
            }
            //申请售后
            boolean refund = true;
            //仅退款 只有代发货才有仅退款
            boolean refundAmt = orderDetailsModel.getR_status() > DictionaryConst.OrdersStatus.ORDERS_R_STATUS_UNPAID;
            //换货 未发货没有换货
            boolean refundGoods = orderDetailsModel.getR_status() > DictionaryConst.OrdersStatus.ORDERS_R_STATUS_CONSIGNMENT;
            //换货 订单两次换货成功后不能再换货  --禅道47399
            if (returnOrderModelMapper.getOrderReturnGoodsNum(storeId, orderDetailsModel.getId(), orderDetailsModel.getR_sNo()) >= 2){
                refundGoods =false;
            }
            //退货退款 未发货没有退货退款
            boolean refundGoodsAmt = orderDetailsModel.getR_status() > DictionaryConst.OrdersStatus.ORDERS_R_STATUS_CONSIGNMENT;
            //查看售后按钮
            boolean refundShowBtn = false;
            //申请退款按钮 如果订单完成了则显示 售后按钮 否则显示退款按钮 俩按钮只有文字上的区别;插件只显示申请售后按钮
            boolean isRefundAmtBtn = (DictionaryConst.OrdersType.ORDERS_HEADER_GM.equalsIgnoreCase(oType) || DictionaryConst.OrdersType.ORDERS_HEADER_PT.equalsIgnoreCase(oType)) && orderDetailsModel.getR_status() > DictionaryConst.OrdersStatus.ORDERS_R_STATUS_UNPAID && ORDERS_R_STATUS_COMPLETE != orderDetailsModel.getR_status();
            //获取售后信息
            ReturnOrderModel returnOrderModel = returnOrderModelMapper.getReturnOrderInfo(storeId, orderDetailsModel.getId(), orderDetailsModel.getR_sNo());
            out:
            if (returnOrderModel != null) {
                int row;
                /*
                //超过售后次数 禅道:37024
                row= returnOrderModelMapper.orderRefundCount(storeId, orderDetailsModel.getR_sNo(), orderDetailsModel.getId());
                if (row >= GloabConst.LktConfig.RETURN_ORDER_LIMIT) {
                    refund = refundAmt = refundGoods = refundGoodsAmt = isRefundAmtBtn = false;
                    break out;
                }*/
                //判断有无售后未结束
                int unFinishShouHouOrderNum = returnOrderModelMapper.orderDetailReturnIsNotEnd(storeId, orderDetailsModel.getR_sNo(), orderDetailsModel.getId());
                //订单每个商品可以申请n次售后,成功才计算  申请换货成功后不能退款！
                if (unFinishShouHouOrderNum > 0) {
                    //有售后未结束不能申请售后
                    refund = refundAmt = refundGoods = isRefundAmtBtn = refundGoodsAmt = false;
                    //显示查看售后按钮
                    refundShowBtn = true;
                } else {
                    //判断是否申请过换货,申请换货成功后不能退款
                    ReturnOrderModel returnOrderCount = new ReturnOrderModel();
                    returnOrderCount.setStore_id(storeId);
                    returnOrderCount.setsNo(orderDetailsModel.getR_sNo());
                    returnOrderCount.setR_type(DictionaryConst.ReturnOrderStatus.RETURNORDERSTATUS_AFTER_SALE_END);
                    returnOrderCount.setRe_type(DictionaryConst.ReturnRecordReType.RETURNORDERSTATUS_GOODS_REBACK);
                    row = returnOrderModelMapper.selectCount(returnOrderCount);
                    if (row > 0) {
                        //有成功记录 换货可以换两次,如果只成功了一次则再次显示申请售后按钮
                        refundAmt = false;
                        refundGoodsAmt = false;
                        //超过换货次数
                        if (row >= GloabConst.LktConfig.RETURN_ORDER_LIMIT) {
                            refund = false;
                            //超过换货次数不显示查看售后按钮
                            refundShowBtn = false;
                            isRefundAmtBtn = false;
                        }
                    }
                }
            }
            //退款是否有成功记录
            if (DictionaryConst.OrdersType.ORDERS_HEADER_GM.equalsIgnoreCase(oType) || DictionaryConst.OrdersType.ORDERS_HEADER_PT.equalsIgnoreCase(oType) || DictionaryConst.OrdersType.ORDERS_HEADER_PS.equalsIgnoreCase(oType) || DictionaryConst.OrdersType.ORDERS_HEADER_FS.equalsIgnoreCase(oType)) {
                //退款是否有成功记录
                int row = returnOrderModelMapper.orderReturnSuccessNum(storeId, orderDetailsModel.getR_sNo(), orderDetailsModel.getId());
                if (row > 0) {
                    refund = refundAmt = refundGoods = refundGoodsAmt = isRefundAmtBtn = false;
                    //52463 【JAVA开发环境】订单（管理后台）：已经退款的订单，订单总价应该不能改变，可以在订单详情中加退款的标识
                    refundShowBtn = true;
                } else {
                    //失败了则显示申请售后
                    refund = true;
                }
            } else {
                //其它插件只能申请换货
                refundAmt = false;
                refundGoodsAmt = false;
            }

            //积分订单、人工审核没有售后
            if (DictionaryConst.OrdersType.ORDERS_HEADER_IN.equalsIgnoreCase(oType)) {
                refund = refundAmt = refundGoods = refundGoodsAmt = refundShowBtn = false;
            }
            //竞拍订单没有售后
            if (DictionaryConst.OrdersType.ORDERS_HEADER_JP.equalsIgnoreCase(oType)) {
                refund = refundAmt = refundGoods = refundGoodsAmt = isRefundAmtBtn = refundShowBtn = false;
            }
            //订单是否已经结算,已经结算了没有售后
            if (orderDetailsModel.getSettlement_type().equals(DictionaryConst.WhetherMaven.WHETHER_OK)) {
                refund = refundAmt = refundGoods = refundGoodsAmt = isRefundAmtBtn = false;
            }

            //订单已完成,判断是否已过了售后期,过了受后期不显示售后按钮
            if (ORDERS_R_STATUS_COMPLETE == orderDetailsModel.getR_status()) {
                String mchId = StringUtils.trim(orderModel.getMch_id(), SplitUtils.DH);
                try {
                    publicOrderService.orderAfterSaleExpire(storeId, Integer.parseInt(mchId), oType, orderDetailsModel.getArrive_time());
                } catch (LaiKeAPIException l) {
                    refund = refundAmt = refundGoods = refundGoodsAmt = isRefundAmtBtn = false;
                }
            }
            //代发货订单有极速退款不显示售后按钮 禅道 53624
            if(ORDERS_R_STATUS_CONSIGNMENT == orderModel.getStatus()
                    && DictionaryConst.OrdersType.ORDERS_HEADER_GM.equalsIgnoreCase(oType)){
                refund = refundAmt = refundGoods = refundGoodsAmt = isRefundAmtBtn = false;
            }
            if (refund) {
                refund = refundAmt || refundGoods || refundGoodsAmt || isRefundAmtBtn;
            }
            //自提订单没有搜后
            if (orderModel.getSelf_lifting() == 1) {
                refund = refundAmt = refundGoods = refundGoodsAmt = isRefundAmtBtn = refundShowBtn = false;
            }
            //有售后未结束不能申请售后
            resultMap.put("refund", refund);
            resultMap.put("refundAmt", refundAmt);
            resultMap.put("refundGoods", refundGoods);
            resultMap.put("refundAmtBtn", isRefundAmtBtn);
            resultMap.put("refundShowBtn", refundShowBtn);
            resultMap.put("refundGoodsAmt", refundGoodsAmt);
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            logger.error("售后按钮是否能显示 异常", e);
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "afterSaleButtonShow");
        }
        return resultMap;
    }

    @Autowired
    private PublicRefundService publicRefundService;

    @Autowired
    private ServiceAddressModelMapper serviceAddressModelMapper;

    @Autowired
    private CustomerModelMapper customerModelMapper;

    @Autowired
    private OrderModelMapper orderModelMapper;

    @Autowired
    private MchModelMapper mchModelMapper;

    @Autowired
    private ReturnOrderModelMapper returnOrderModelMapper;

    @Autowired
    private PublicMemberService publicMemberService;

    @Autowired
    @Qualifier("publicAlipayServiceImpl")
    private PublicPaymentService publicAlipayServiceImpl;

    @Autowired
    @Qualifier("publicWechatServiceImpl")
    private PublicPaymentService publicWechatServiceImpl;

    @Autowired
    private PubliceService publiceService;

    @Autowired
    private MessageListModelMapper messageListModelMapper;

    @Autowired
    private MchAccountLogModelMapper mchAccountLogModelMapper;

    @Autowired
    private ConfiGureModelMapper confiGureModelMapper;

    @Autowired
    private ProductListModelMapper productListModelMapper;

    @Autowired
    private StockModelMapper stockModelMapper;

    @Autowired
    private OrderDetailsModelMapper orderDetailsModelMapper;

    @Autowired
    private ReturnGoodsModelMapper returnGoodsModelMapper;

    @Autowired
    private ExpressModelMapper expressModelMapper;

    @Autowired
    private ReturnRecordModelMapper returnRecordModelMapper;

    @Autowired
    private SystemMessageModelMapper systemMessageModelMapper;

    @Autowired
    private PublicCouponService publicCouponService;

    @Autowired
    private PreSellRecordModelMapper preSellRecordModelMapper;

    @Autowired
    private SignRecordModelMapper signRecordModelMapper;

    @Autowired
    private UserBaseMapper userBaseMapper;

    @Autowired
    private PublicIntegralService publicIntegralService;

    @Autowired
    private SupplierOrderFrightModelMapper supplierOrderFrightModelMapper;

    @Autowired
    private SupplierModelMapper supplierModelMapper;

    @Autowired
    private SupplierAccountLogModelMapper supplierAccountLogModelMapper;

    @Autowired
    private ExpressDeliveryModelMapper expressDeliveryModelMapper;

}

